前端如何上传图片到七牛云
流程:
1、七牛云后台的对象存储功能
2、node.js后台生成七牛云的token
3、前端利用element UI/ice 的upload组件
4、文件名和token作为参数请求到七牛云后台
第一步 node.js后台生成七牛云的token
token
const accessKey = 'TSlScX_akS5TIpsXlkq*****7Efk-ZaZeg4ZWtta';
const secretKey = 'X-MGLySWVrWFIQKTn***WDIBvb3ni4Zm3qwZNKxk';
const bucket = 'deluntiyun';
如何获取这三个参数
accessKey 就是AK
secretKey 就是SK
bucket 就是你的空间名字
我的token是koa后台请求回来的,附上代码 node的话qiniu模块
非node的话自行查询Node.js SDK
let qiniu = require('qiniu'); // 需要加载qiniu模块的
const accessKey = 'TSlScX_akS5TIpsXl****gy7Efk-ZaZeg4ZWtta';
const secretKey = 'X-MGLySWVrWFI****87HWDIBvb3ni4Zm3qwZNKxk';
const bucket = 'deluntiyun';
router.post('/token', async(ctx, next)=> {
let mac = new qiniu.auth.digest.Mac(accessKey, secretKey);
let options = {
scope: bucket,
expires: 3600 * 24
};
let putPolicy = new qiniu.rs.PutPolicy(options);
let uploadToken= putPolicy.uploadToken(mac);
if (uploadToken) {
ctx.body = Code('re_success', uploadToken)
} else {
ctx.body = Code('re_error')
}
})
token也是在前端来生成的, 加载qiniu模块,利用其方法就可以生成token
第二步 上传到七牛云 - Vue
ui框架 element-ui el-upload
koa2 请求到七牛云的token
let qiniu = require('qiniu'); // 需要加载qiniu模块的
const router = require('koa-router')()
router.prefix('/api/admin/qiniu')
let config = {
"AK":"TSlScX_akS5TIpsXlkqHH2gy7Efk-ZaZeg4ZWtta",
"SK":"X-MGLySWVrWFIQKTn87HWDIBvb3ni4Zm3qwZNKxk",
"Bucket":"mobile-phone-shell"
}
router.post('/token', async(ctx, next)=> {
let mac = new qiniu.auth.digest.Mac(config.AK, config.SK);
let code = '1',msg = '', data = {};
let options = {
scope: config.Bucket,
expires: 3600 * 24
};
let putPolicy = new qiniu.rs.PutPolicy(options);
let uploadToken= putPolicy.uploadToken(mac);
if (uploadToken) {
code = '0';
data.uploadToken = uploadToken;
ctx.body = {code, data, msg}
} else {
ctx.body = {code, data, msg}
}
})
module.exports = router
前端代码
<el-upload
<el-upload
style='position: relative;top: 10px;height: 120px;'
:file-list='fileList'
class="avatar-uploader"
:limit='1'
:action="uploadUrl"
accept="image/jpeg,image/gif,image/png,image/bmp"
list-type="picture-card"
:data='uploadData'
:on-success="handleAvatarSuccess"
:on-error="uploadError"
:before-upload="beforeAvatarUpload"
:on-preview="doLookImg"
:on-remove="doDeleteImg">
<i class="el-icon-plus"></i>
</el-upload>
<script>
export default {
data() {
return {
uploadUrl: 'http://up-z0.qiniu.com',
uploadData: {key:'',token:''},
formAdd: { brandLogo: '' }
}
},
mounted() {
getQiniuToken({}).then((res)=> {
console.log(res);
if (res.code === '0') {
this.uploadData.token = res.data.uploadToken
}
})
},
methods: {
doDeleteImg(file, fileList) {
console.log('删除成功',file, fileList)
let logoAry;
let key;
if (this.editState) {
logoAry = this.mainInfo.brandLogo.split('/');
} else {
logoAry = this.formAdd.brandLogo.split('/');
}
key = logoAry[logoAry.length - 1];
deleteQiniuImg({key}).then(res=> {
if (res.code === '0') {
if (this.editState) {
this.mainInfo.brandLogo = '';
} else {
this.formAdd.brandLogo = '';
}
} else {
this.$message.error(res.msg)
}
})
},
doLookImg() {
this.uploadDialogVisible = true;
this.uploadDialogImg = this.editState ? this.mainInfo.brandLogo : this.formAdd.brandLogo;
},
handleAvatarSuccess(res, file, fileList) {
console.log('上传成功', res,file, fileList)
let hash = res.hash;
let key = res.key;
if (this.editState) {
this.mainInfo.brandLogo = qiniuConfig.qiniuPath + '/' + key;
} else {
this.formAdd.brandLogo = qiniuConfig.qiniuPath + '/' + key;
}
},
beforeAvatarUpload(file) {
console.log(file, 'beforeAvatarUpload')
// var observable = qiniu.upload(file, key, token, putExtra, config)
const isPNG = file.type === "image/png";
const isJPEG = file.type === "image/jpeg";
const isJPG = file.type === "image/jpg";
const isLt2M = file.size / 1024 / 1024 < 2;
if (!isPNG && !isJPEG && !isJPG) {
this.$message.error("上传头像图片只能是 jpg、png、jpeg 格式!");
return false;
}
if (!isLt2M) {
this.$message.error("上传头像图片大小不能超过 2MB!");
return false;
}
this.uploadData.key = `upload_pic_${new Date().getTime()}_${file.name}`;
},
uploadError(err, file, fileList) {
this.$message({
message: "上传出错,请重试!",
type: "error",
center: true
});
},
}
}
</script>
作者:sponing
链接:https://www.jianshu.com/p/7520e0bee777
来源:简书