使用 egg.js + superagent 進行文件上傳轉發
// app/controller/file.js
const Controller = require('egg').Controller;
const fs = require('fs')
const request = require('superagent')
const sendToWormhole = require('stream-wormhole')
const toArray = require('stream-to-array');
const path = require('path');
const uuid = require('uuid/v1');
class FileController extends Controller {
async file() {
const { ctx, app } = this;
// 獲取上傳的文件
let stream;
try {
stream = await ctx.getFileStream();
} catch (e) {
console.error('文件不存在或者文件錯誤');
}
if (!stream) {
ctx.throw(403,'文件不存在或者文件錯誤')
return false;
}
const nameid = uuid().replace(/-/g, '');
const filename = nameid + '.' + stream.filename.toLowerCase().split('.').pop();
// 文件暫時存在 app/public 文件夾下
const target = path.join(this.config.baseDir, 'app/public', filename);
const url = '上傳地址';
// 使用 superagent 上傳
try {
// 轉化stream
const parts = await toArray(stream);
let buf = Buffer.concat(parts);
// 寫入文件保存至本地
fs.writeFileSync(target, buf);
// 上傳
const res = await request
.post(url)
.attach('file', target, filename)
ctx.body = res.text;
} catch (err) {
// 必須將上傳的文件流消費掉,要不然瀏覽器響應會卡死
await sendToWormhole(stream);
ctx.throw(500,'文件上傳出錯');
}
// 因為只做臨時保存,在上傳完畢后刪除文件
fs.unlink(target, function (err) {
if (!err) {
console.log('文件已刪除:', target);
}
});
}
}
module.exports = FileController;
地址資源鏈接
superagent官方文檔
egg文件上傳參考文檔