概述
下载文件
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/
最后
以上就是彩色冬瓜为你收集整理的如何在nodejs里使用axios上传和下载文件下载文件上传文件的全部内容,希望文章能够帮你解决如何在nodejs里使用axios上传和下载文件下载文件上传文件所遇到的程序开发问题。
如果觉得靠谱客网站的内容还不错,欢迎将靠谱客网站推荐给程序员好友。
本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
发表评论 取消回复