我正在使用 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? )
接下来是什么?如何创建一个强制下载该图像的视图?
您可以尝试这段代码,也许需要一些注意事项:
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
我假设有一个字段.name
在你的ImageModel
获取倒数第二行中的文件名...filename=%s" % img.name
您应该编辑代码以适合您的项目。
中有一个字段图像场那是file
,在这里的代码中我使用img.file
要获取文件的路径,您应该将其更改为img.YOUR_IMAGE_FIELD.file
或任何您需要获取图像路径的内容
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)