javascript - 如何使用 python 将 BLOB 转换为图像
问题描述
我需要使用 blob 将图像从客户端发送到服务器
我已将图像转换为BLOB
jquery(客户端)并将 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()
解决方案
不要将文件作为文本读取,您正在处理二进制数据。
使用 json 传输二进制文件的最佳方法是,如果您将文件读取为 base64,reader.readAsDataURL(file)
这会将所有字节编码为 Web 安全的 base64 字符串(无斜线或加号)。然后你也必须用 python 解码它。我不鼓励您在处理文件传输时使用 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] })
推荐阅读
- javascript - 在javascript变量中渲染flask jinja表单
- javascript - 如何获取所有特定按钮并单击赛普拉斯中具有特定数据ID的每个按钮
- excel - VBA,Excel:如何将图表添加到选定范围内
- c# - 使用继承的类型作为实例 getter 的包装器
- rust - 我可以在不手动实现序列化或反序列化的情况下序列化字段子集并使用函数反序列化其他字段吗?
- c++ - 传递给类时 c_str() 和字符串的奇怪行为
- python - 如何编辑python字典中可变的键
- python - 通过其方法或属性找到一个类对象。可以做到吗?
- javascript - 一起调试节点和客户端 Javascript
- javascript - 使用引导程序在表中显示数据