提问者:小点点

如何将上传图像保存到flask中的文件夹中


我用ajax保存上传的图像并发布它。 我尝试用flask保存文件,但得到如下错误。 你能帮帮我吗?

这个js代码

var image = $("#imageUpload")[0].files[0];
    var data = {
        "image": image.name,
        "image_type": image.type, 
    }
  $.ajax({
         url: "/home",
         type: "POST",
         data: JSON.stringify(data),
         contentType: "application/json; charset=utf-8"
         })

此烧瓶代码

image_name = json_data[0]['image']
image_type = json_data[0]['image_type']
full_image = FileStorage(folder_path, image_name, content_type=image_type)
image_name = 'photo_' + data['uname'] + '_' + created_date + '_' + created_time + '.' + str(image_type.split('/')[1])
folder_path = 'static/img/'
image_path = folder_path + image_name
if not folder_path:
    os.mkdir(folder_path)
full_image.save(image_path)

此错误消息

full_image.save(image_path)文件“...\venv\lib\site-packages\werkzeug\datastructures.py”,第3070行,在保存copyfileobj(self.stream,dst,buffer_size)文件“c:\program files\python38\lib\shutil.py”中,第199行,在copyfileobj fsrc_read=fsrc.read attributeerror:“str”对象没有属性“read”


共1个答案

匿名用户

您只是将一些字符串传递给处理程序(“image”和“image_type”)。 您需要将实际的数据文件(图像)从web页面发布到后端。 然后使用:

FileStorage(image, image_name, content_type=image_type)

此函数无法从客户端上的文件夹路径读取文件。 它需要流作为字节:

image_bytes = image.read()