nodeJS结合七牛云,multer,express实现多图上传

nodeJS结合七牛云,multer,express实现多图上传

可能不是最好实现方式,因为7牛云只能单图上传,要注意删除图片和返回给前端的时机一定要对

Router.post('/qiniuUpload', upload.array('file', 5), function (req, res, next) {
    var file = req.files
    var arrPath = []
    for (var i = 0; i < file.length; i++) {
        var pathName = "upload/" + file[i].filename + '.' + file[i].originalname.split('.')[1]
        fs.rename(req.files[i].path, pathName, function (err) {
            if (err) {
                throw err;
            }
        })
        arrPath.push({path: path.resolve(pathName)})
    }
    console.log(arrPath)
    var imgs = []
    if (arrPath.length > 0) {
        for (let i = 0; i < arrPath.length; i++) {
            var paths = 'upload/' + Math.random().toString().split('.')[1] + Date.now() + '.jpg'
            formUploader.putFile(uploadToken, paths, arrPath[i].path, putExtra, function (respErr, respBody, respInfo) {
                if (respErr) {
                    throw respErr;
                }
                if (respInfo.statusCode == 200) {
                    imgs.push(configs.qiniu.URL + respBody.key)
                    if (arrPath.length-1 === i) { // 图片上传七牛云完毕
                        for (let j = 0; j < arrPath.length; j++) {
                            fs.unlinkSync(arrPath[j].path)
                        } // 删除在本地的图片
                        res.json({code: 0, data: imgs}) // 返回前端七牛云图片数组
                    }
                } else {
                    console.log(respInfo)
                    if (respInfo.statusCode === 401) {
                        formUploader.putFile(uploadToken, paths, arrPath[i].path, putExtra, function (respErr, respBody, respInfo) {
                        })
                    }
                }
            })
        }
    }
})

你可能感兴趣的:(nodeJS结合七牛云,multer,express实现多图上传)