擅长:python、mysql、java
<p>您可以尝试此代码,可能需要一些注意事项:</p>
<pre><code>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
</code></pre>
<ol>
<li><p>我假设在您的<code>ImageModel</code>中有一个字段<code>.name</code>来获取文件名的倒数第二行<code>...filename=%s" % img.name</code>您应该编辑代码以适合您的项目。</p></li>
<li><p>在<strong><em>image field</em></strong>中有一个字段,即<code>file</code>,在这里的代码中,我使用<code>img.file</code>来获取文件的路径,您应该将其更改为<code>img.YOUR_IMAGE_FIELD.file</code>或获取图像路径所需的任何内容</p></li>
</ol>