我想前端上传图片到七牛云。
后端眼睛配置好了,但是前端的element-ui
不知道怎么样配置,用axios
请求也是不行。
所以想问问看,前端怎么样配置才更好的河后端相通,使图片上传到七牛云中。
后端
var express = require('express');
var router = express.Router();
const multiparty = require('connect-multiparty');
const path = require('path');
let uploadDir = path.resolve(__dirname, '../temp');
let multipartMiddleware = multiparty({uploadDir});
router.post('/upload', multipartMiddleware, function(req, res, next) {
console.log(req.files);
const qiniu = require("qiniu");
//需要填写你的 Access Key 和 Secret Key
qiniu.conf.ACCESS_KEY = '...';
qiniu.conf.SECRET_KEY = '...';
//要上传的空间
bucket = 'image';
//构建上传策略函数
function uptoken(bucket, key) {
let putPolicy = new qiniu.rs.PutPolicy(bucket+":"+key);
return putPolicy.token();
}
//构造上传函数
function uploadFile(uptoken, key, localFile, resolve, reject) {
let extra = new qiniu.io.PutExtra();
qiniu.io.putFile(uptoken, key, localFile, extra, function(err, ret) {
if(!err) {
// 上传成功, 处理返回值
resolve(localFile);
console.log(ret.hash, ret.key, ret.persistentId);
} else {
// 上传失败, 处理返回代码
reject(err);
}
});
}
// 构造Promise数组
let promiseArr = [];
for (index in req.files) {
let p = new Promise((resolve, reject) => {
//上传到七牛后保存的文件名
key = req.files[index].originalFilename;
key = Date.now().toString() + encodeURI(key.split('.')[0]) + '.' + key.split('.')[1]
//生成上传 Token
token = uptoken(bucket, key);
//要上传文件的本地路径
filePath = req.files[index].path;
//调用uploadFile上传
uploadFile(token, key, filePath, resolve, reject);
})
promiseArr.push(p);
}
// 所有异步执行完成之后返回成功
let pAll = Promise.all(promiseArr);
pAll.then((localFile) => {
console.log(localFile);
res.json({code: 1})
}, (err) => {
console.log(err);
res.json({code: 0, msg: '上传失败'});
})
});
module.exports = router;
前端
<body>
<el-dialog title="图片上传" v-model="isUploadShow">
<el-upload
action="//up.qbox.me/"
type="drag"
:thumbnail-mode="true"
:on-success="handleSuccess"
:before-upload="beforeUpload"
:data="form"
>
<i class="el-icon-upload"></i>
</el-upload>
</el-dialog>
</body>
<script>
new Vue({
el:'#app',
data () {
return {
form: {}
}
},
methods: {
beforeUpload (file) {
},
handleSuccess (response, file, fileList) {
},
}
})
</script>
在线等
我是用原生方法传递的。new formdata()