下载文件
var res = await axios.get(url,{responseType : "stream"});
示例:
在koa2的get请求里从别处下载文件后直接转回给前端
const 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}`);
});
上传文件
?示例:从别的网络下载文件后,再上传到另外一个网站上
const 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/
|