node egg.js 上傳圖片到第三方圖片儲存伺服器方法
// 上傳 image 檔案 方法1: form表單 2:圖片轉base64編碼
async imageFile(ctx) {
let result = { message: 'upload failed', status:'FAILED' };
//let result = { message:'http://qukufile2.qianqian.com/data2/pic/90392fb17371a44e39097fd00846ef97/66087/66087.jpg@s_1,w_300,h_300', status:'SUCCEED' };
let baseDir = ctx.app.baseDir;
const stream = await ctx.getFileStream();
const filename = path.basename(stream.filename);
// 判斷 upload_file 資料夾是否存在, 不存在則建立
const dirExists = fs.existsSync(path.join(baseDir, './upload_file/image'));
if (!dirExists) {
fs.mkdirSync(path.join(baseDir, './upload_file/'));
fs.mkdirSync(path.join(baseDir, './upload_file/image'));
}
const target = path.join(baseDir, './upload_file/image/', filename);
const writeStream = fs.createWriteStream(target);
try {
// 寫入檔案
await awaitStreamReady(stream.pipe(writeStream));
} catch (err) {
// 必須將上傳的檔案流消費掉,要不然瀏覽器響應會卡死
await sendToWormhole(stream);
result['message'] = 'write stream fail!';
throw err;
}
let picDir = ctx.request.body.picDir || 'image'
let remoteFileName = "d4/pic/cms/"+picDir+"/"+filename
let remoteUrl = "http://img.XXX.org/"+ remoteFileName
// 呼叫介面上傳
const form = new FormStream();
form.file('file', target);
let postResult;
let base64fileUpload= async()=>{
var imageBuf = fs.readFileSync(target);
var base64Img = imageBuf.toString('base64');
try {
postResult = await ctx.curl('http://XXX:6003/mw/upload?sign=n_e_m_o&filename=' + remoteFileName, {
method: 'POST',
data: {
base64file: base64Img,
},
headers: form.headers(),
});
if (postResult.data && postResult.status === 200) {
result['status'] = 'SUCCEED';
result['message'] = remoteUrl;
}
} catch (error) {
this.ctx.logger.error(`upload image base64file:${error}`);
}
}
try {
postResult = await ctx.curl('http://XXX:6003/mw/upload?sign=n_e_m_o&filename=' + remoteFileName, {
method: 'POST',
headers: form.headers(),
stream: form,
timeout: 1000 * 120, // 2m內請求完成
});
if (postResult.data && postResult.status === 200) {
result['status'] = 'SUCCEED';
result['message'] = remoteUrl;
}
} catch (error) {
this.ctx.logger.error(`upload image stream form:${error}`);
await base64fileUpload()
}
ctx.body = result;
}