我的需求就是前端提交图片之后,自动上传到七牛云中。
前端提交图片之后出现500
错误,请问一下到底哪里出错了。
后端
const router = require('express').Router();
const qiniu = require('qiniu');
qiniu.conf.ACCESS_KEY = 'you key';
qiniu.conf.SECRET_KEY = 'you key';
router.post('/upload', (req,res) => {
const uptoken = (bucket,key) => {
let putPolicy = new qiniu.rs.PutPolicy(bucket + ':' + key);
return putPolicy.token();
}
const uploadFile = (uptoken,key,localfile) => {
qiniu.io.putFile(uptoken, key, localFile, extra, function(err, ret) {
if(!err) {
// 上传成功, 处理返回值
return res.json({
hash: ret.hash,
key: ret.key,
per: ret.persistentId
});
} else {
// 上传失败, 处理返回代码
console.log(err);
}
});
}
const bucket = 'image';
const key = req.body.key;
const token = uptoken(bucket,key,req.files[0].path)
uploadFile(token,key,req.files[index].path)
})
module.exports = router;
index.html
<body>
<div id="app">
<el-upload
action="https://upload.qbox.me"
:data="dataObj"
drag
:multiple="true"
:before-upload="beforeUpload"
:on-success='handleSuccess'>
<i class="el-icon-upload"></i>
<div class="el-upload__text">将文件拖到此处,或<em>点击上传</em></div>
</el-upload>
</div>
</body>
<script>
new Vue({
el: '#app',
data:{
dataObj: { token: '', key: '' },
image_uri: [],
fileList: []
},
methods:{
beforeUpload(file) {
const tath = this;
const name = file.name;
const curr = Date.now().toString();
const key = encodeURI(`${curr}_${name}`);
return new Promise((resolve,reject) => {
axios.post('/api/qiniu/upload',{ key }).then(res => {
consoel.log(res.data);
that.data.dataObj.token = res.data.token;
tath.data.dataObj.key = res.data.key;
resolve(true);
}).catch(err => {
console.log(err);
reject(false);
})
});
},
handleSuccess() {
console.log('上传成功')
}
}
})
</script>
500是后台程序有问题,没看到你后台怎么接受前端传的文件,我之前是先用 multiparty 处理了一下,可以给你参考下。