转自简书: https://www.jianshu.com/p/7520e0bee777
前端如何上传图片到七牛云
流程: 生成token => token和图片作为new FromData() 参数 再上传
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_akS5TIpsXlkqHH2gy7Efk-ZaZeg4ZWtta'; const secretKey = 'X-MGLySWVrWFIQKTn87HWDIBvb3ni4Zm3qwZNKxk'; 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
上传到七牛云 - React
upload组件 ice Upload 上传组件
// 用来删除图片的 onUploadChange(info) { if (info.file.status == 'removed') { this.setState({ fileList: [], values: Object.assign({ avatar: '' }) }) } } <Col xxs="16" s="10" l="6"> <IceFormBinder name="avatar" required message="必填"> <ImageUpload listType="picture-card" limit={1} action={this.state.qiniu.url} fileList={this.state.fileList} accept="image/png, image/jpg, image/jpeg, image/gif, image/bmp" data={this.state.qiniuToken} locale={{ image: { cancel: '取消上传', addPhoto: '上传图片', }, }} formatter={(res)=>{ // 七牛云返回的数据 { hash:"FjIEDVNzhgmsU7cOBtkAXV7VuhvJ",key:"FjIEDVNzhgmsU7cOBtkAXV7VuhvJ"} let imgURL = this.state.qiniu.qiniuPath + "/" + res.key; this.setState({ fileList: [{ status: "done", downloadURL: imgURL, fileURL: imgURL, imgURL: imgURL }], value: Object.assign(this.state.value, { avatar: imgURL }) }) }} onChange= {this.onUploadChange.bind(this)} /> </IceFormBinder> </Col>
附上网友大神的ice组件代码,虽然不是用七牛云的
上传到七牛云 - 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>