From: 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';
如何獲取這三個參數

image.png
accessKey 就是AK
secretKey 就是SK

image.png
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組件代碼,雖然不是用七牛雲的

52A911F6-D3A8-4cb0-A041-202644CCA761.png
上傳到七牛雲 - 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>