下载文件
复制代码
1
2var res = await axios.get(url,{responseType : "stream"});
示例:
在koa2的get请求里从别处下载文件后直接转回给前端
复制代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21const Koa = require('koa'); const Router = require('koa2-router') const axios = require('axios') const app = new Koa(); const router = new Router(); const port = 3000; router.get('/download',async (ctx, next) => { const url = <url from other website> var res = await axios.get(url,{responseType : "stream"}); ctx.set("Content-Type", res.headers['content-type']); ctx.response.body = res.data; }); app.use(router); app.listen(port,() => { console.log(`web app started, listening at ${port}`); });
上传文件
示例:从别的网络下载文件后,再上传到另外一个网站上
复制代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17const axios = require('axios'); const FormData = require('form-data') const upload = async () => { var url = <the url from other website>; var res = await axios.get(url,{responseType : "stream"}); const formData = new FormData(); formData.append("test",'test'); formData.append("file",res.data,fileName); await axios.post(<uploadUrl>, formData, { headers: formData.getHeaders(), maxBodyLength: Infinity }); }
参考: Send a File With Axios in Node.js - Maxim OrlovEverything you need to know about sending files with axios in Node.js — from creating a form to setting the right headers.https://maximorlov.com/send-a-file-with-axios-in-nodejs/
[Solved] Axios Error: Request body larger than maxBodyLength limit | ProgrammerAHhttps://programmerah.com/solved-axios-error-request-body-larger-than-maxbodylength-limit-38597/
最后
以上就是彩色冬瓜最近收集整理的关于如何在nodejs里使用axios上传和下载文件下载文件上传文件的全部内容,更多相关如何在nodejs里使用axios上传和下载文件下载文件上传文件内容请搜索靠谱客的其他文章。
本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
发表评论 取消回复