【问题标题】:In Express.js, why does my downloaded file have a different size to the server file size?在 Express.js 中,为什么我下载的文件大小与服务器文件大小不同?
【发布时间】:2019-08-04 22:42:34
【问题描述】:

我的 express.js 代码很简单:

app.get("/download", download);

export let download = async (req: Request, res: Response) => {
  const file = "/tmp/my-file.zip";
  res.download(file);
}

我的客户端代码也很简单:

import axios from "axios";
const fileDownload = require("js-file-download");

axios.get("/download").then(response => {
  fileDownload(response.data, "export.zip");
});

从浏览器下载时,文件已损坏,无法打开。原来的/tmp/my-file.zip119506 字节。奇怪的是,下载的export.zip216980 字节。我目前在本地运行所有内容,因此没有操作系统差异可以解释这一点。

为什么我的文件大小不同(导致 .zip 文件损坏),我该如何解决?

编辑 - 这些是浏览器标题:

accept-ranges: "bytes"
cache-control: "no-store, no-cache, must-revalidate, proxy-revalidate"
connection: "keep-alive"
content-disposition: "attachment; filename="my-file.zip""
content-length: "119506"
content-type: "application/zip"
date: "Thu, 14 Mar 2019 06:04:28 GMT"
etag: "W/"1d2d2-1697acd3f53""
expires: "0"
last-modified: "Thu, 14 Mar 2019 06:04:25 GMT"
pragma: "no-cache"
referrer-policy: "no-referrer"
surrogate-control: "no-store"
x-content-type-options: "nosniff"
x-frame-options: "SAMEORIGIN"
x-xss-protection: "1; mode=block"

【问题讨论】:

  • 您得到的响应类型是 json 吗?
  • 我已经编辑了我的问题以包含浏览器标题。它应该是一个基于内容类型的 zip 文件。
  • 如果你只是用浏览器导航到/download会发生什么?
  • @felixmosh 很好的测试,效果很好。我猜 axios 或 js-file-download 是改变文件的东西。
  • 那么为什么要通过ajax来使用呢?只需在上面放一个带有download 属性的链接,它就会下载文件:]

标签: javascript node.js express


【解决方案1】:

我在post 找到了解决方案。因为axios responseType 默认是json

// responseType 表示服务器将要发送的数据类型 响应 // 选项是 'arraybuffer', 'blob', 'document', 'json', 'text', 'stream' responseType: 'json', // 默认

axios.get('/download',{ responseType:'arraybuffer'})
.then(function (response) {
    console.log('########### HEADERS: ', response.headers);
    console.log('########### AXIOS: ', response.data.length);
  fileDownload(response.data, "export.zip");
});

希望它有效:)

【讨论】:

    猜你喜欢
    • 2011-04-22
    • 1970-01-01
    • 1970-01-01
    • 2019-01-20
    • 2015-12-18
    • 2017-12-14
    • 1970-01-01
    • 2020-08-15
    • 2012-08-04
    相关资源
    最近更新 更多