koa2使用阿里雲oss的nodejs sdk實現上傳圖片

nodejs實現上傳圖片到阿里雲,天然是寫成接口形式比較方便,前端監聽input file的改變,把file對象傳入到formData中傳入後端,不能直接傳入file對象,後端須要接受formDatahtml

其餘中間件推薦:前端

formidable  node

connect-multipartyios

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

 

個人代碼地址:https://github.com/beileixinqing/aliyun-oss-upload

相關文章
相關標籤/搜索