我想将图像作为附件发送。我的代码:resp = FileResponse(open(fullImgPath, "rb"))resp['Content-Disposition'] = 'attachment; filename="{}"'.format(os.path.basename(fullImgPath))resp["Content-Type"]="image/%s"%('png' if fullImgPath.endswith('png') else 'jpeg')return resp它确实有效,如果我通过requests. 但是当我通过浏览器(chrome 和 firefox)下载文件时,文件已损坏。我如何通过浏览器(javascript)做到这一点:$.get(requestUrl) .success(function(data, textStatus, request){ SaveBlob(data, "1,jpeg", "image/jpeg") } })function SaveBlob(blob, fileName, contentType) { var a = document.createElement('a'); a.href = window.URL.createObjectURL(new Blob([blob], { "type" : contentType })); a.download = fileName; a.dispatchEvent(new MouseEvent('click'));}它以前有效!今天我发现我得到的文件已损坏。但是,存储在服务器上的文件是普通图像。怎么了?
1 回答

慕尼黑5688855
TA贡献1848条经验 获得超2个赞
Jquery 不会将文件内容下载为二进制文件,因此您的图像已损坏。看起来 jquery 不支持下载为二进制文件,但您可以使用原生 xhr:
function SaveBlob(blob, fileName, contentType) {
var a = document.createElement('a');
a.href = window.URL.createObjectURL(new Blob([blob], {"type": contentType}));
a.download = fileName;
a.dispatchEvent(new MouseEvent('click'));
}
var oReq = new XMLHttpRequest();
oReq.open("GET", requestUrl, true);
oReq.responseType = "arraybuffer";
oReq.onload = function (oEvent) {
SaveBlob(oReq.response, '1.jpg', 'image/jpg')
};
oReq.send();
想知道它以前是如何工作的。
添加回答
举报
0/150
提交
取消