【问题标题】:Get Django download attachment from web-browser从网络浏览器获取 Django 下载附件
【发布时间】:2019-05-17 13:03:55
【问题描述】:

我想将图片作为附件发送。

我的代码:

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'));
}

它以前工作过!今天我发现我得到的文件已损坏。但是,存储在服务器上的文件是普通图像。

怎么了?

【问题讨论】:

  • 你在 js 中有语法错误。 .success 已弃用 - 应使用 .done。 Js 不完整 - 没有 getFname()getCtype()ParseRespHeaders()。除此之外,django 方面还不错。
  • 这是我自己的函数,从解析头返回字符串文件名和字符串内容类型。对于测试,这可以用作 SaveBlob(data, '1.jpeg', 'image/jpeg') 。工作解决方案仅 open(requestUrl, '_blank') 。是否可以在不损坏文件的情况下以 ajax 方式保存 blob?
  • 如果您使用 ajax 获取它,在我看来您不需要使用 Content-Disposition“附件”返回它。不确定这是否有什么不同?

标签: javascript django browser attachment


【解决方案1】:

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();

想知道它以前是如何工作的。

【讨论】:

    猜你喜欢
    • 2014-04-16
    • 1970-01-01
    • 2011-02-04
    • 2010-10-23
    • 2013-02-24
    • 1970-01-01
    • 2016-06-23
    • 2012-12-21
    • 2017-06-02
    相关资源
    最近更新 更多