以下方式皆用formidable: https://www.npmjs.com/package/formidable
一、方式1
文件一個一個的轉存
router.post(url, (req, res) => {
let form = formidable.IncomingForm({
encoding : 'utf-8',//上傳編碼
uploadDir : temp_floder,//上傳目錄,指的是服務器的路徑,如果不存在將會報錯。
keepExtensions : true,//保留后綴
maxFieldsSize : 10 * 1024 * 1024//byte//最大可上傳大小
});
let fields = {}; //formdata攜帶的參數信息
form.on('field', (name, value) => { //field事件會先file事件觸發
fields[name] = value;
})
.on('file', async (filename, file) => {
// 可根據fields自由組合目錄結構
let resource_file_path = path.join(fields[index1], fields[index2], file.name);
// 剪切文件,將帶一串代碼的文件,轉存為正常命名與后綴的文件
await moveFile(file.path, resource_file_path);
})
.on('end', () => {
res.status(200).json({code: '1000', msg: '上傳成功'});
})
.on('error', (err) => {
res.status(400).json({code: '0000', msg: '上傳失敗'});
})
.parse(req, (err, fields, files) => {});
})
二、方式2
解析出所有參數與文件后,一起轉存
router.post(url, (req, res) =>{
let form = formidable.IncomingForm({
encoding : 'utf-8',//上傳編碼
uploadDir : temp_floder,//上傳目錄,指的是服務器的路徑,如果不存在將會報錯。
keepExtensions : true,//保留后綴
maxFieldsSize : 10 * 1024 * 1024//byte//最大可上傳大小
});
form.parse(req, async (err, fields, files) => {
let resource_file_path;
for(let file in files) {
resource_file_path = path.join(fields[index1], fields[index2], file.name);
// 剪切文件,將帶一串代碼的文件,轉存為正常命名與后綴的文件
await moveFile(file.path, resource_file_path);
}
})
})