Skip to main content
 首页 » 编程设计

python之Django 没有考虑图像

2024年08月23日27飞鱼

我试图让用户上传一个图像文件,然后它应该自动转换成 base64 字符串。

所以我的输入表单看起来像,

<form role="form" method="POST" action="{% url 'Guideform-edit' object.pk %}" 
              class="post-form form-horizontal">{% csrf_token %} 
            <!-- customizing form --> 
            {{ form|crispy }} 
            <!-- End of customization --> 
            <div style="position:relative;"> 
                <a class='btn btn-primary' href='javascript:;'> 
                    Choose File... 
                    <input type="file" 
                           style='position:absolute;z-index:2;top:0;left:0;bottom:0;right:0;filter: alpha(opacity=0);-ms-filter:"progid:DXImageTransform.Microsoft.Alpha(Opacity=0)";opacity:0;background-color:transparent;color:transparent;' 
                           name="file_source" size="40" onchange='$("#upload-file-info").html($(this).val());'> 
                </a> 
                &nbsp; 
                <span class='label label-info' id="upload-file-info"></span> 
            </div> 
            <button type="submit" class="save btn btn-default btn-primary center-block">Update</button> 
 
        </form> 

对应的 View 类是这样的,

class GuideFormUpdateView(UpdateView): 
    model = Guide 
    fields = ['name', 'image', 'point_of_interest'] 
    template_name_suffix = '_update_form' 
 
    def post(self, request, *args, **kwargs): 
        query_dict = request.POST 
        img = Image.open(StringIO(query_dict['file_source'])) 
        print img 

我得到的错误是,

File "/home/avinash/django_projects/guide/src/guide/views.py" in post 
  166.         img = Image.open(StringIO(query_dict['file_source'])) 
 
File "/home/avinash/.virtualenvs/guide/local/lib/python2.7/site-packages/PIL/Image.py" in open 
  2295.                   % (filename if filename else fp)) 
 
Exception Type: IOError at /guides/edit/1 
Exception Value: cannot identify image file <StringIO.StringIO instance at 0x7f427ab4c6c8> 

我还尝试打印 query_dict 变量,

print query_dict 

我得到的输出是,

{u'csrfmiddlewaretoken': u'xxxxxxxxxxx', u'name': u'pieza tower', u'file_source': u'20150706_104718.jpg'} 

所以,它似乎将上传的图像作为字符串而不是实际图像。

请您参考如下方法:

这里有几件事:

  1. 上传文件需要指定enctype="multipart/form-data"表单属性

  2. 文件存储在request.FILES ,而不是 request.POST

最后,要实际转换为 base64,您可以使用该模块

encoded_img = base64.b64encode(filehandler.read()) 

其中 filehandler 是 request.FILES 中文件的处理程序

此外,您似乎没有通过 Django 表单加载 input type='file'。让 django 表单处理验证可能是一个更好的主意,这样您就不会遇到安全问题等。(您可以限制输入文件类型等。),