nodejs實現上傳圖片到阿里雲,自然是寫成接口形式比較方便,前端監聽input file的改變,把file對象傳入到formData中傳入后端,不能直接傳入file對象,后端需要接受formData
其他中間件推薦:
上傳單張:
最終找到了github上一個朋友用formidable寫的,非常好用,代碼戳這里
我根據該文件實現了上傳圖片的代碼如下:
nodejs文件:
exports.uploadFile = async (ctx,next) => { let alioss_uploadfile = function() { return new Promise(function(resolve, reject) { //上傳單文件,使用formidable let form = new formidable.IncomingForm() form.parse(ctx.req, function(err, fields, files) { if (err) { ctx.throw('500',err)} // 文件名 let date = new Date() let time = '' + date.getFullYear() + (date.getMonth() + 1) + date.getDate() let filepath = 'project/'+time + '/' + date.getTime() let fileext = files.file.name.split('.').pop() let upfile = files.file.path let newfile = filepath + '.' + fileext //ali-oss co(function*() { client.useBucket('p-adm-test') let result = yield client.put(newfile, upfile) console.log('文件上傳成功!', result.url) let data=[] data.push(result.url) ctx.response.type = 'json' ctx.response.body = { errno: 0, data: data } resolve(next()) }).catch(function(err) { console.log(err) }) }) }) } await alioss_uploadfile() }
但是發現這個中間件只支持上傳單文件,如果上傳多文件,需要multiparty中間件
上傳多張:
參考鏈接:https://www.cnblogs.com/wuwanyu/p/wuwanyu20160406.html
我實現的代碼:
exports.uploadFile = async (ctx,next) => { let alioss_uploadfile = function() { return new Promise(function(resolve, reject) { //上傳多文件,使用multiparty let form = new multiparty.Form({ encoding: 'utf-8', keepExtensions: true //保留后綴 }) form.parse(ctx.req, async function (err, fields, files) { let data=[] for(let f of files.file){ // 文件名 let date = new Date() let time = '' + date.getFullYear() + (date.getMonth() + 1) + date.getDate() let filepath = 'project/'+time + '/' + date.getTime() let fileext = f.originalFilename.split('.').pop() let upfile = f.path let newfile = filepath + '.' + fileext await client.put(newfile, upfile).then((results) => { console.log('文件上傳成功!', results.url) data.push(results.url) }).catch((err) => { console.log(err) }) } ctx.response.type = 'json' ctx.response.body = { errno: 0, data: data } resolve(next()) }) }) } await alioss_uploadfile() }
這里有個for循環,多次執行的阿里雲sdk,把返回的鏈接push到data數組里,最后返回,如果像上邊一樣用co實現,則最終
ctx.response.body
返回的data只有第一張圖片的url,之后的並不能返回,應該是異步問題導致,這里自己學的還不精通,不明白其中解決辦法和原理,期望有大神可以解惑!!!感激不盡!!
問題描述在這里===》https://segmentfault.com/q/1010000015425832
如果使用了koa2-multiparty中間件,則函數中的參數files獲取不到,而是直接通過ctx.req.files獲取傳過來的file列表
koa2-multiparty: https://www.npmjs.com/package/koa2-multiparty