Skip to main content
 首页 » 编程设计

python之如何在 Django 中提供可下载的图像文件

2025年05月04日33qq号

我将所有图像存储在项目中的某个文件夹(如媒体)中,并且我在 html 模板中有一个按钮可以下载相应的图像。

下面是我的代码

views.py

@login_required 
def download_image(request, product_id): 
    import os 
    # current_site = get_current_site(request) 
    product_image =  Product.objects.get(id=product_id) 
    product_image_url = product_image.image_code_url() 
    print product_image_url, ">>>>>>>>>>>>>>>" 
    response = HttpResponse(mimetype='application/force-download') 
    response['X-Sendfile'] = smart_str(product_image_url) 
    response['Content-Length'] = os.stat(product_image_url).st_size 
 
    return response   

template.html

<input type=button><a href="{% url 'download_image' product_id%}"></a>/> 

结果:

/media/productb7ab/product792f2764314f40b8bd3b3d58290765cc/codes/Image_1.png  >>>>>>>>>>>>>>> 
ERROR 2013-10-25 18:46:21,192 (base) (7258, -1248855232): Internal Server Error: /download/code/88/ 
Traceback (most recent call last): 
  ....... 
  ....... 
  OSError: [Errno 2] No such file or directory: '/media/productb7ab/product792f2764314f40b8bd3b3d58290765cc/codes/Image_1.png' 

但是当我点击像 localhost:8000/media/productb7ab/product792f2764314f40b8bd3b3d58290765cc/codes/Image_1.png 这样的 url 时,我可以查看图像,

那么最后如何在 Django 中从文件系统下载图像?

我在上面的代码中做错了什么?

编辑

阅读 Brandon 分享的建议链接后

我已经将上面的方法修改为下面的代码,但仍然面临同样的错误

从 django.core.servers.basehttp 导入 FileWrapper

@login_required 
def downloadimage(request, product_id): 
    import os 
    # current_site = get_current_site(request) 
    image_code =  Product.objects.get(object_id=product_id) 
    image_code_url = image_code.image_code_url() 
    print image_code_url,">>>>>>>>>>>>>>" 
    wrapper = FileWrapper(file(image_code_url)) 
    response = HttpResponse(wrapper, content_type='text/plain') 
    response['Content-Disposition'] = 'attachment; filename=%s' % os.path.basename(image_code_url) 
    response['Content-Length'] = os.path.getsize(image_code_url) 
    return response 

错误

Error:IOError at /download/code/88/ 
[Errno 2] No such file or directory: '/media/productrbab/product792f2764314f40b8bd3b3d58290765cc/codes/Image_1.png' 
Request Method: GET 
Request URL:    http://localhost:8000/download/qrcode/88/ 
Django Version: 1.5.4 
Exception Type: IOError 
Exception Value:     
[Errno 2] No such file or directory: '/media/productrbab/product792f2764314f40b8bd3b3d58290765cc/codes/Image_1.png' 

请您参考如下方法:

为什么不在之前的 View 中设置url:

image_url = Product.objects.get(...).image_code_url() 

然后只需在您的模板中放置一个普通链接:

<a href="{{ image_url }}">Download</a> 

注意:在较大的系统中通过 Django 提供文件会导致效率低下 - 最好通过简单的 HTTP 服务器(Apache 或 Nginx)提供文件。有关媒体管理的更多信息,请参阅 django docs .