【问题标题】:File Streams Wtih Axios使用 Axios 进行文件流
【发布时间】:2020-09-09 19:14:03
【问题描述】:

我需要使用 Axios 从流中下载文件。我不认为这是服务器的问题,因为如果我使用 http 包,它就可以工作。这是我的代码:

export function downloadRequest (savePath, reqURL, currentFile, serverPath) {
  const file = fs.createWriteStream(savePath[0] + `/${currentFile}`)
  axios({
    method: 'get',
    url: `${storedIP}${reqURL}`,
    responseType: 'stream',
    headers: {
      Authorization: `Bearer ${token}`
    }
  }).then(function (reponse) {
    reponse.data.pipe(file)
    hashCheck(currentFile, savePath, serverPath)
  })

但是这会返回以下两个错误: the provided value 'stream' is not a valid enum value of type XMLHttpRequestResponseType. Uncaught (in promise) TypeError: reponse.data.pipe is not a function

我试着做这篇文章中所说的:Type error this.httpClient.get(...).pipe is not a function

但这使得一个窗口弹出说这样的话:

windows script host 

Script: c:\npm\node_modules\webpack\bin\webpack.js
Line: 1
Char: 1
Error: Invalid character
Code: 800A03F6
Source: Microsoft JScript compilation error

我进入了那个 js 文件,第 1 行是#!/usr/bin/env node

我也尝试卸载 webpack 并重新安装,但没有帮助。

注意:如果这很重要,我正在使用带有类星体的 Axios。

【问题讨论】:

  • “我需要使用 Axios 从流中下载文件”——为什么?错误消息表明 Axios 不支持流,并且您说您有一个使用 http 模块的有效解决方案。
  • 这是在服务器上,还是你使用electron或类似的东西?
  • @Quentin 好吧,我想我不需要,我只是喜欢 Axios 的一些功能,例如:axios.defaults.headers.common['Authorization'] = AUTH_TOKEN; 和:onDownloadProgress allows handling of progress events for downloads alos 在文档中说:responseType indicates the type of data that the server will respond with options are: 'arraybuffer', 'document', 'json', 'text', 'stream' 跨度>
  • @MarcosCasagrande 我正在使用电子和类星体,但这不在服务器上。服务器只是普通的nodejs,但正在另一台电脑上运行
  • 检查我的答案。

标签: javascript node.js


【解决方案1】:

如果您使用的是 electron,则应将适配器设置为 http 而不是 XMLHttpRequest

axios.defaults.adapter = require('axios/lib/adapters/http');

如果你得到 response.data.pipe 不是一个函数,那么你似乎只能在主线程中将 response.data 作为流获取:

https://github.com/axios/axios/issues/1474#issuecomment-380594110

ipcRenderer.send("downloadRequest"); // when downloadRequest is called

主线程

app.on("ready", async () => {

 // other electron setup

 ipcMain.on("downloadRequest", (event, arg) => {
   // axios download code here
 });
});

【讨论】:

  • 去掉了the provided value 'stream' is not a valid enum value of type XMLHttpRequestResponseType. 但response.data.pipe(file) is not a function 还在
  • 你还在用responseType: 'stream'吗?因为它应该工作。显示确切的堆栈跟踪。
  • 是的,我还有responseType: 'stream',我很困惑,你说的痕迹是什么意思?
  • 错误,你得到的确切错误。复制并粘贴堆栈跟踪(控制台中显示的错误,带有线条等)
  • 好吧,这就是说的:``` RESTrequests.js?d591:96 Uncaught (in promise) TypeError: response.data.pipe is not a function at eval (RESTrequests.js? d591:97) (匿名)@RESTrequests.js?d591:96 Promise.then (async) downloadRequest@RESTrequests.js?d591:88 downloadFn@Table.vue?a2a3:177 click@Table.vue?bc0c:48 invokeWithErrorHandling@ vue.runtime.esm.js?2b0e:1854 调用者@vue.runtime.esm.js?2b0e:2179 original._wrapper@vue.runtime.esm.js?2b0e:6911 ```
【解决方案2】:

在电子版本 9.0.4 中,不需要下面的行

axios.defaults.adapter = require('axios/lib/adapters/http');   

在渲染器中

ipcRenderer.send("download_file");

在您的主要使用下面的代码

ipcMain.on("download_file", (event, args) => {
        var url = "YourFileUrl";
    
        // console.log(data)
    
        require("axios").get(url, { responseType: 'stream' })
          .then(res => {
            var fileName = res.headers['content-disposition'].split("=")[1].split("\"")[0];
           
            const writer = require('fs').createWriteStream("Location to save the file");
    
            new Promise((resolve, reject) => {
    
              res.data.pipe(writer);
              let error = null;
    
              writer.on('error', err => {
                error = err;
                writer.close();
                reject(err);
              });
    
              writer.on('close', () => {
                if (!error) {
                  resolve(true);
                }
                //no need to call the reject here, as it will have been called in the
                //'error' stream;
              });
            });
          }).catch((error) => {
            console.log(error)
          });    
      }

);

参考:

node.js axios download file and writeFile

【讨论】:

    猜你喜欢
    • 2019-02-26
    • 1970-01-01
    • 2018-08-08
    • 1970-01-01
    • 2020-09-21
    • 2012-02-21
    • 2018-08-27
    • 2019-08-02
    • 2018-04-06
    相关资源
    最近更新 更多