【问题标题】:Django downloading image using ImageFieldDjango使用ImageField下载图像
【发布时间】:2020-12-15 13:57:02
【问题描述】:

我正在尝试创建一个 Django 应用程序,允许用户从 /images/ 文件夹(类似于我的应用程序中的静态文件夹)上传和下载图像。我的 upload 部分应用使用 ImageField 将图像文件路径存储到 MySQL 数据库中:

models.py

class ImagefieldModel(models.Model): 
    title = models.CharField(max_length = 200) 
    img = models.ImageField(upload_to = "images/")

    class Meta:
        db_table = "imageupload"

forms.py

class ImagefieldForm(forms.Form): 
    name = forms.CharField() 
    image_field = forms.ImageField() 

fileupload.html

{% extends "main/header.html" %}
 

 {% block content %}
      <head>
        <title>Django File Upload</title>
      </head>
      <body>
          <form method="POST" enctype="multipart/form-data"> 
              {% csrf_token %} 
              {{ form.as_p }} 
              <input type="submit" value="Submit"> 
          </form> 
      </body>
 {% endblock %}

views.py

def imgupload(request): 
    context = {}
    if request.method == "POST": 
        form = ImagefieldForm(request.POST, request.FILES) 
        if form.is_valid(): 
            name = form.cleaned_data.get("name") 
            img = form.cleaned_data.get("image_field") 
            obj = ImagefieldModel.objects.create( 
                                 title = name,  
                                 img = img 
                                 ) 
            obj.save() 
            print(obj)
            messages.info(request, f"image uploaded successfully!")
            return redirect("main:basehome")
    else: 
        form = ImagefieldForm()
        context['form'] = form
        return render( request, "main/fileupload.html", context) 

对于我的应用程序的下载部分,我希望该应用程序列出/image/ 文件夹中的所有图像,并且用户可以选择要下载到其下载文件夹中的图像。使用 ImageField 时如何在 Django 中执行此操作?

【问题讨论】:

  • 您现在遇到的语法错误是什么?
  • @markwalker_ 我设法找到了另一种选择。我只是使用“ImagefieldModel.objects.all()”从文件中获取所有要显示的图像,然后右键单击“下载”图像。不过如果有办法下载图像文件会很好。通过用户单击下载按钮下载特定图像。

标签: python django


【解决方案1】:

您需要将图像添加到响应对象。类似的东西;


    def get(self, request, *args, **kwargs):

        # first get the instance of your model from the database
        imagefieldinstance = self.get_object()

        # Then get the URL of the image to download
        url = imagefieldinstance.img.url
        try:
            # Download the image to the server
            img = requests.get(url)
            if not 200 <= img.status_code < 400:
                raise Http404()

        except Exception as e:
            raise Http404() from e

        # Figure out the mimetype of the file
        mime_type, _ = mimetypes.guess_type(url)

        # Get the file extension
        _, extension = os.path.splitext(url.split('/')[-1])

        # Create the filename of the download
        filename = '{}{}'.format(
            slugify(imagefieldinstance.title),
            extension
        )

        # Add the content of the (image) file to the response object
        response = HttpResponse(
            img.content,
            content_type=mime_type
        )
        response['Content-Disposition'] = \
            'attachment; filename="{}"'.format(filename)

        # Send the user the response
        return response

【讨论】:

  • 感谢您的回复。您能否解释一下代码的每个部分的作用?我还是 Django 的新手
  • @Reallynoobatprogramming 我添加了 cmets。
  • 我在使用您建议的代码时遇到了错误,如下面的回答所示。你能帮我修一下吗?您还可以指导我需要修改哪些部分以适合我系统的下载部分吗?我还删除了一些像“raise Http404()”这样的部分,以避免任何错误,因为我在开发环境中这样做。非常感谢您的帮助
  • 如果我可以通过其他方式与您联系会更好吗? Discord 或其他我可以向您展示代码的东西,您可以帮助我即时调试。我没有时间完成我的系统,这个下载是唯一阻止我的部分。
  • 如果您遇到无法解决的新问题,请提出其他问题
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-02-08
  • 2018-11-27
  • 1970-01-01
  • 2019-09-04
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多