koa2使用阿里云oss的nodejs sdk实现上传图片

nodejs实现上传图片到阿里云,自然是写成接口形式比较方便,前端监听input file的改变,把file对象传入到formData中传入后端,不能直接传入file对象,后端需要接受formData

其他中间件推荐:

formidable  

connect-multiparty

multiparty

koa2-multiparty

上传单张:

最终找到了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

我的代码地址:https://github.com/beileixinqing/aliyun-oss-upload

原文地址:https://www.cnblogs.com/beileixinqing/p/9152113.html