前端使用ElementUi中的Upload 上传图片
在后端node服务器需要安装两个库:
npm install qiniu
npm install multer
node服务器我使用的是express
这里需要添加处理文件中间件:
const multer = require('multer')
const upload = multer({ dest: 'uploads/' });
//处理文件
app.use(upload.single('file'));
处理请求响应:
const express = require('express');
const router = express.Router();
var accessKey = 'xxx'; //七牛云密钥AK
var secretKey = 'xxx'; //七牛云密钥SK
var mac = new qiniu.auth.digest.Mac(accessKey, secretKey);
router.post('/', function (req, res, next) {
var options = {
scope: 'xxx',//空间名
};
var putPolicy = new qiniu.rs.PutPolicy(options);
var token = putPolicy.uploadToken(mac); //获取token
const file = req.file; //获取上传文件
const key = file.originalname;
var config = new qiniu.conf.Config();
var formUploader = new qiniu.form_up.FormUploader(config);
var putExtra = new qiniu.form_up.PutExtra();
formUploader.putFile(token, key, file.path, putExtra, function (respErr,
respBody, respInfo) {
if (respErr) {
throw respErr;
}
if (respInfo.statusCode == 200) {
const { key } = respBody; //获取上传成功后的key
res.json({
src: 'xxxx七牛云空间域名' + key
})
} else {
res.json({
err: '上传失败'
})
}
});
});
module.exports = router;
注:在上传之前需要先在七牛云开通空间