Django从ImageField下载图像

2024-04-28 09:30:38 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在使用Django 1.7和Python 3.4。

我有一个这样的模型:

class ImageModel(models.Model):
    image = models.ImageField(verbose_name='image', upload_to='uploaded_images/')

现在我想下载保存在/static/uploaded_images/中的图像。 例如,我有一个这样的链接:www.example.com/image/download/1,其中1是ImageModel对象的id。

现在我有一个观点:

def download_image(request, image_id):
     img = ImageModel.objects.get(id=image_id)
     ( what I need to do? )

接下来呢?如何创建将强制下载该图像的视图?


Tags: todjango模型图像imageidverbosemodel
3条回答

您需要使用Content-Disposition头,请查看以下内容:

Generating file to download with Django
Django Serving a Download File

您可以尝试此代码,可能需要一些注意事项:

from django.core.servers.basehttp import FileWrapper
import mimetypes

def download_image(request, image_id):
    img = ImageModel.objects.get(id=image_id)
    wrapper      = FileWrapper(open(img.file))  # img.file returns full path to the image
    content_type = mimetypes.guess_type(filename)[0]  # Use mimetypes to get file type
    response     = HttpResponse(wrapper,content_type=content_type)  
    response['Content-Length']      = os.path.getsize(img.file)    
    response['Content-Disposition'] = "attachment; filename=%s" %  img.name
    return response
  1. 我假设在您的ImageModel中有一个字段.name来获取文件名的倒数第二行...filename=%s" % img.name您应该编辑代码以适合您的项目。

  2. image field中有一个字段,即file,在这里的代码中,我使用img.file来获取文件的路径,您应该将其更改为img.YOUR_IMAGE_FIELD.file或获取图像路径所需的任何内容

其他两个答案是可以的,但是在许多地方,由于性能原因,不建议使用Django来提供静态文件。最好使用您的web服务器(nginx/apache…)提供服务。

您不需要额外的视图来提供静态文件。只需在模板中呈现指向文件的链接:

<a href="{{object.image.url}} download">Download this image!</a>

其中objectImageModel的实例。

django.db.models.fields.files.FieldFile.url

如果您真的想在像www.example.com/image/download/1这样的URL中拥有一个视图,您可以简单地编写一个视图,重定向到从该字段获得的图像URL。

相关问题 更多 >