javascript - 有谁知道为什么 res.download 每次都给我的下载文件一个随机名称?

标签 javascript node.js express download

我正在使用 express 4.17.1。当我尝试使用 res.download 将 csv 文件发送到浏览器时,文件已下载,但文件名如下所示:3d6a8bc1-696c-40f2-bae8-29ca69658534.csv

然后,当我尝试再次下载同一个文件时,它会以这个名称发送文件:c1cd40ff-ea9d-4327-9389-9768fb53384a.csv

每次都是不同的随机字符串。

我的代码很简单:

res.download(filePath, 'list.csv');

文件路径是这样的:./downloadables/mail-list-14da.csv

我试过使用 sendFile 但得到了相同的结果。我最近更新了以前版本的 express,看看它是否会自动解决这个问题,但它仍在这样做。

编辑:根据要求在下方添加更多代码

这里是整个请求端点:

/*
 * Download the list specified by the list_id with the appropriate fields as specified by the
 * list_type parameter.
 */
router.get('/download/:list_type/:list_id', authCheck('list'), function(
  req,
  res,
  next
) {
  let listData = {};

  Voter.aggregate(aggrPipelineList(req.params.list_type, req.params.list_id))
    .allowDiskUse(true)
    .exec()
    .then(voterDocs => {
      if (voterDocs && voterDocs.length === 0) {
        res.status(404).json({
          message: `list_id ${req.params.list_id} not found`
        });
      } else {
        listData.voter_docs = voterDocs;
        return req.params.list_type;
      }
    })
    .then(listType => {
      if (listType === 'mail') {
        return generateMailExportFile(req.params.list_id, listData);
      } else if (listType == 'phone') {
        return generateCallExportFile(req.params.list_id, listData);
      } else {
        return generateFacebookExportFile(req.params.list_id, listData);
      }
    })
    .then(filePath => {
      console.log('FP: ' + filePath);
      res.download(filePath, 'list.csv');
    })
    .catch(err => {
      res.status(500).json({ message: err.message }); // @note: added message
    });
});

为了完整性,还包括 generateMailExportFile 函数。是的,我知道我可以重构三个生成导出文件的函数。它在我的 list 上......我最初写这篇文章之前我还不知道我到底在做什么。

generateMailExportFile = function(listID, listData) {
  let fields = [
    'First Name',
    'Last Name',
    'Suffix',
    'Street Address 1',
    'Street Address 2',
    'City',
    'State',
    'Zip'
  ];
  let fileName = 'mail-list-' + listID.substr(listID.length - 4) + '.csv';
  let voterRows = buildVoterRowsForMailList(listData.voter_docs);
  let csv = json2csv({ data: voterRows, fields: fields });
  let tempServerFilePath = './downloadables/' + fileName;
  return new Promise((resolve, reject) => {
    fs.writeFile(tempServerFilePath, csv, function(err) {
      if (err) {
        reject(err);
      } else {
        resolve(tempServerFilePath);
      }
    });
  });
};

这是请求文件下载的 redux/thunk 函数:

export const downloadList = (listId, type) => {
  return (dispatch, getState) => {
    const rshttp = new RSHttp(getState);
    rshttp
      .get('/list/download/' + type + '/' + listId)
      .then(response => {
        let file = new Blob([response.data], { type: 'text/csv' }),
          url = window.URL.createObjectURL(file);
        window.open(url);
      })
      .catch(error => {
        console.log('Error Downloading File: ' + JSON.stringify(error));
      });
  };
};

我之前没有考虑过 react 方面的问题。如果我找到答案,我会更新这个问题。任何想法仍然非常感谢!

最佳答案

问题是您正在前端重新创建文件。您只需将 React 代码更改为:

export const downloadList = (listId, type) => {
  return (dispatch, getState) => {
    window.open('http://localhost:8080/list/download/' + type + '/' + listId', '_blank')
    // Replace with your backend URL :)
  };
};

它会下载具有正确文件名的文件。

关于javascript - 有谁知道为什么 res.download 每次都给我的下载文件一个随机名称?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57959108/

相关文章:

javascript - Angular2 .filter 对象数组

javascript - 如何清除 Javascript 中的单选按钮?

javascript - 如何在 node.js 中异步递归 API 回调?

javascript - 你如何使用mongodb native、express和body-parser来发布请求和保存数据?

javascript - 异步/等待操作发生在预期的顺序之外

javascript - 将鼠标悬停在选项内容上时下拉框消失

javascript - 等待客户端响应来运行代码socket.io?

node.js - 处理 Node.JS 中类的函数调用

javascript - Node 解压。如何制作文件名

node.js - socket.io - 第一次工作,而不是第二次