nodejs实现上传图片到阿里云,天然是写成接口形式比较方便,前端监听input file的改变,把file对象传入到formData中传入后端,不能直接传入file对象,后端须要接受formDatahtml
其余中间件推荐:前端
formidable node
multipartygit
koa2-multipartygithub
上传单张:npm
最终找到了github上一个朋友用formidable写的,很是好用,代码戳这里json
我根据该文件实现了上传图片的代码以下:segmentfault
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