【问题标题】:Set the filename for file download with use of Fetch()使用 Fetch() 设置文件下载的文件名
【发布时间】:2021-05-31 04:33:43
【问题描述】:

尝试了不同的标题解决方案,但无法设置下载文件的文件名:

NodeJs 服务器端(快递):

res
.set('content-disposition', `attachment; filename="${filename}";  filename*=UTF-8''${encodeURI(filename)}`) // filename header
.type('.xlsx') // setting content-type to xlsx. based on file extention
wb.write(filename, res);

客户端(React + JS):

const options = {
      headers: {
        'Content-Disposition': 'attachment; filename="filename.xlsx";'
      }
    };
    fetch("/api", options)
      .then( res => res.blob() )
      .then( blob => {
        var file = window.URL.createObjectURL(blob);
        window.location.assign(file);
    });

我在客户端收到了正确的文件,但文件名类似于“93e43995-e4c2-4184-af62-a268d0b456e2.xlsx”。

在客户端控制台(网络选项卡)我可以看到:

Request URL: blob:https://192.168.0.34:8443/e60d73fb-b423-4176-beb3-103028f8f225
Request Method: GET
Status Code: 200 OK
Referrer Policy: strict-origin-when-cross-origin
Content-Length: 5823
Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet
Provisional headers are shown
Upgrade-Insecure-Requests: 1

如何设置标题以设置文件名?某处可能是错误的语法?请不要提供带有 JS a href 对象的答案,例如 a.click。这与我的情况不兼容。

Apoorva 的更新,谢谢,看起来不错,但出现了一些错误:

 Unexpected token, expected ","

  252 |              const filename =  response.headers.get('Content-Disposition').split('filename=')[1];
  253 |              return {response: res.blob(), filename: filename}})
> 254 |       .then( ({response, filename} => {
      |                                    ^

请再检查一次好吗?

【问题讨论】:

    标签: javascript node.js reactjs express


    【解决方案1】:

    在将响应转换为 blob 之前,您需要从标头中获取它。

    const options = {
          headers: {
            'Content-Disposition': 'attachment; filename="filename.xlsx";'
          }
        };
        fetch("/api", options)
          .then( res => {
                 const filename =  res.headers.get('Content-Disposition').split('filename=')[1];
                 return {response: res.blob(), filename: filename}})
          .then( ({response, filename}) => {
            var file = window.URL.createObjectURL(response);
            window.location.assign(filename);
            console.log(filename)
        }).catch((e) => {console.log(e)})
    
    

    【讨论】:

    • 感谢您的回复,有帮助,但出现了错误。请检查更新的问题。我尝试自己调试,但您的编辑可能会更快?
    • 现在检查,我已经更新了答案,只是一个错字。
    • 它说 - 第 252:32 行:'response' 未定义 no-undef。在行中 - const filename = response.headers.get('Content-Disposition').split('filename=')[1];我已尝试更改对 res 的响应,但文件未下载。
    • 它会抛出任何错误吗?另外,请尝试检查文件名。它现在应该可以工作了。然后放入一个调试器并检查它的运行情况。
    • 因为响应可能是尝试这个`window.URL.createObjectURL(new Blob(response, {type: "provide type"}));`。可能是即将到来的响应不是 blob,这就是为什么尝试让控制台检查这些对象的值可能有助于调试。
    猜你喜欢
    • 1970-01-01
    • 2016-08-26
    • 1970-01-01
    • 1970-01-01
    • 2018-08-23
    • 1970-01-01
    • 1970-01-01
    • 2020-10-30
    • 1970-01-01
    相关资源
    最近更新 更多