首页 > 解决方案 > 如何使用 python 将 BLOB 转换为图像

问题描述

我需要使用 blob 将图像从客户端发送到服务器

我已将图像转换为BLOBjquery(客户端)并将 blob 发送到 python 烧瓶(服务器端)问题是,我无法从BLOB. 我在python中尝试了以下代码但未能获取图像

将图像转换为 blob 的 Jquery 代码:

function changeFile() {
     var file = this.files[0];
     var reader = new FileReader();
     reader.addEventListener('load', readFile);
     reader.readAsText(file);
}

function readFile(event) {
     document.body.textContent = event.target.result;
     console.log(event.target.result);
     appendFileAndSubmit(event.target.result);
}


function appendFileAndSubmit(imageUrl){
     var ImageURL = imageUrl
     var data = {
          'logo':ImageURL
          }
             $.ajax({
                        url: 'http://sdsdss/User/imgBlob',
                        method: 'POST',
                        dataType : 'json',
                        data: JSON.stringify(data),
                        contentType: 'application/json; charset=utf-8'
                    }).done(function(response){    
                        var datas = JSON.parse(response);
                        console.log(datas);
                    });
                }
document.getElementById("inp").addEventListener("change", changeFile);

Python代码:重新创建BLOB图像

function getImage(self):
     reqData = json.loads(request.data)
     Logo = reqData['logo']
     png_recovered = base64.decodestring(Logo)
     f = open("temp.png", "w")
     f.write(png_recovered)
     f.close()

标签: javascriptpythonajaxflaskblob

解决方案


  1. 不要将文件作为文本读取,您正在处理二进制数据。
    使用 json 传输二进制文件的最佳方法是,如果您将文件读取为 base64,reader.readAsDataURL(file)这会将所有字节编码为 Web 安全的 base64 字符串(无斜线或加号)。然后你也必须用 python 解码它。

  2. 我不鼓励您在处理文件传输时使用 json ,因为它会增加大约 3 倍的带宽(更不用说来回解码和编码所需的时间)为此,我建议您改用FormData


var fd = new FormData()
fd.append('logo', files[0])

$.ajax({
  url: 'http://sdsdss/User/imgBlob',
  method: 'POST',
  data: fd,
  // Setting false prevent jQuery from transforming the data
  processData: false,
  contentType: false
}).then(function(response) {
  console.log(JSON.parse(response))
})

或者更简单,如果不需要,只需发布​​没有任何 formdata、json 或额外字段的文件。

fetch(uploudUrl, { method 'PUT', body: this.files[0] })

推荐阅读