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

时间:2020-07-22 14:40:54

标签: javascript python flask werkzeug file-storage

我用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 个答案:

答案 0 :(得分:1)

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

FileStorage(image, image_name, content_type=image_type)

此功能无法从客户端上的文件夹路径读取文件。它需要以字节为单位的流:

image_bytes = image.read()