一、Axios上傳文件終止
在使用Axios上傳文件時,需要注意上傳的請求不同於普通的請求。上傳請求需要加入FormData,把需要上傳的文件放入FormData中,最後作為請求體發送至服務端。
// 安裝axios
npm install axios --save
// 文件上傳
let formData = new FormData();
formData.append("file", file);
axios.post("/upload", formData, {
headers: {
"Content-Type": "multipart/form-data"
}
}).then(response => {
console.log(response.data);
}).catch(error => {
console.log(error);
});
上面的代碼是一個簡單的文件上傳示例,其中axios.post方法的第二個參數,就是請求體,需要傳入一個FormData。FormData可以通過new FormData()創建,然後通過formData.append方法把需要上傳的文件添加至其中,最後作為第二個參數傳遞給axios.post方法。
二、Axios傳文件
文件上傳本質上是文件傳輸,因此Axios同樣可以用來傳文件,只需把需要傳輸的文件放入請求體,通過post或其他請求方法發送至服務端即可。下面是一個簡單的代碼示例:
// 安裝axios
npm install axios --save
// 傳文件
let file = fs.readFileSync(path.join(__dirname, "sample.txt"));
axios.post("/upload", file).then(response => {
console.log(response.data);
}).catch(error => {
console.log(error);
});
上面的代碼中,我們讀取了一個sample.txt文件,然後使用axios.post方法將文件作為請求體發送至服務端。這裡要注意的是,上面的代碼只是將文件作為二進位流發送,如果服務端不支持二進位請求,可能會導致請求失敗。
三、Axios上傳文件到Egg
Egg.js是一個基於Node.js和Koa的企業級應用框架,它提供了非常豐富的插件和生態,可以幫助開發者快速搭建企業級應用。在Egg中,文件上傳可以使用egg-multipart插件進行處理。egg-multipart提供了multipart/form-data請求的解析功能,可以很方便地處理文件上傳請求。
下面是一個使用Axios上傳文件到Egg的代碼示例:
// 安裝egg-multipart及axios
npm install egg-multipart axios --save
// 在Egg中引入multiparty
const multiparty = require("multiparty");
// 收到文件上傳請求時
async upload() {
const { ctx } = this;
const form = new multiparty.Form();
form.parse(ctx.req, async (err, fields, files) => {
if (err) {
ctx.status = 500;
ctx.body = err;
return;
}
// 處理文件上傳成功後的邏輯
});
}
// 前端代碼
let formData = new FormData();
formData.append("file", file);
axios.post("/upload", formData, {
headers: {
"Content-Type": "multipart/form-data"
}
}).then(response => {
console.log(response.data);
}).catch(error => {
console.log(error);
});
上面的代碼中,我們首先在Egg中引入了multiparty,實現了文件上傳的請求處理邏輯。在前端,我們把文件添加至FormData中,然後作為請求體發送至服務端。需要注意的是,在axios請求中,我們需要設置Content-Type為multipart/form-data,這樣服務端才能正確地解析請求。
四、總結
本文詳細介紹了使用Axios上傳文件的相關知識。Axios不僅可以實現文件上傳,還可以用來傳輸文件。在使用文件上傳時,需要注意上傳請求需要使用FormData作為請求體,同時需要注意請求頭的設置。此外,在Egg中使用文件上傳時,需要使用multipart/form-data類型的請求,同時需要使用multiparty進行請求的解析。
原創文章,作者:小藍,如若轉載,請註明出處:https://www.506064.com/zh-tw/n/157974.html