一、前端
upload(){
const file = document.querySelector("#file");
const fd = new FormData(); // 需要創建一個表單對象
fd.append("f",file.files[0])
axios({
method:'post',
url: '/api/upload',
data: fd
})
}
二、後端
app.use(koaBody({
multipart: true
})
...
router.post("/api/upload", async (ctx, next) => {
const file = ctx.request.body.files.f;
// 獲取上傳文件,f是表單名稱即name,是自己定義的
const reader = fs.createReadStream(file.path);
const filename = (new Date()).valueOf() + file.name;
let filePath = path.join(__dirname, 'upload/') + `/${filename}`;
// 創建可寫流
const upStream = fs.createWriteStream(filePath);
// 可讀流通過管道寫入可寫流
reader.pipe(upStream);
ctx.body = "success";
})