Django从ImageField下载图像 [英] Django download image from ImageField

查看:39
本文介绍了Django从ImageField下载图像的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用Django 1.7和Python 3.4.

I'm working with Django 1.7 and Python 3.4.

我有一个像这样的模型:

I have a model like this one:

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.

Now I want to download image which is saved in /static/uploaded_images/. For example I have a link like this: www.example.com/image/download/1, where 1 is id of ImageModel object.

现在我有一个观点:

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

接下来要做什么?如何创建将强制下载该图像的视图?

What next? How to create a view that will force download of that image?

推荐答案

您可以尝试以下代码,可能需要注意以下几点:

You can try this code, maybe need some caveats:

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 您应编辑代码以适合您的项目.

  1. I'm assuming there is a field .name in your ImageModel to get the name of the file in the second-to-last line ...filename=%s" % img.name You should edit the code to fit your project.

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

There is a field in an ImageField that is file, in the code here I use img.file to get the path to the file, you should change that for img.YOUR_IMAGE_FIELD.file or anything you need to get the path to the image

这篇关于Django从ImageField下载图像的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆