解释:
AccessKey,SecretKey:秘钥,在这里可以查看到https://portal.qiniu.com/user/key
Bucket:存储空间,在这里可以查看到https://portal.qiniu.com/kodo/bucket
Domain:存储空间Bucket对应的域名,通过这个域名和一个key值可以访问到图片,https://portal.qiniu.com/kodo/bucket/domain?bucketName=BucketName
安装:
npm install qiniu-js
引入:
const qiniu = require('qiniu-js')
// or
import * as qiniu from 'qiniu-js'
data:
fileList: [],
uploadUrl: "http://qiniu.XXXXXXX.com/",//Domain,上传的域名
uploadData: {//上传携带的额外参数
key: "filename", //上传的文件名
token: "", //后端生成的token
},
methods:
handleExceed(d) {
this.$message.error(`最多上传${this.limit}张图片`);
return false;
},
handleDelete(file, fileList) {
console.log("删除成功", file, fileList);
},
handleSuccess(res, file, fileList) {
console.log("上传成功", res, file, fileList);
},
beforeUpload(file) {
console.log("beforeUpload", file);
const isGIF = file.type === "image/gif";
const isPNG = file.type === "image/png";
const isJPEG = file.type === "image/jpeg";
const isJPG = file.type === "image/jpg";
const isBMP = file.type === "image/bmp";
const isLt100M = file.size / 1024 / 1024 < 100;
if (!isPNG && !isJPEG && !isJPG && !isBMP&& !isGIF ) {
this.$message.error("图片只能是 gif,jpg,jpeg,bmp,png 格式!");
return false;
}
if (!isLt100M) {
this.$message.error("图片大小不能超过 100MB!");
return false;
}
},
handleError(err, file, fileList) {
this.$message({
message: "上传出错,请重试!",
type: "error",
center: true,
});
},
//获取后端返回的token
getToken() {
this.$http
.get("http://116.66.66.66:8080/openParkApi/v1/common/qiniu/token")
.then((res) => {
// console.log('qiniu-token',res);
if (res.data.upToken) {
this.uploadData.token = res.data.upToken;
}
});
},
//获取时间戳
getTimeStamp(D,format) {
if(!D){
D=new Date()
}
let year=D.getFullYear()
let month=D.getMonth()+1
let day=D.getDate()
month=month<10?'0'+month:month
day=day<10?'0'+day:day
let hour=D.getHours()
let minute=D.getMinutes()
let second=D.getSeconds()
hour=hour<10?'0'+hour:hour
minute=minute<10?'0'+minute:minute
second=second<10?'0'+second:second
if(format){
return year+'-'+month+'-'+day+' '+hour+":"+minute+":"+second
}else{
return year+month+day+hour+minute+second
}
},
//自定义上传
selfUpload(d) {
const _this=this
let key = this.getTimeStamp() + "_" + d.file.size + d.file.name;
let putExtra = {};
let config = {useCdnDomain: true};
// file:图片数据;key:图片名称;token:服务端获取的token;putExtra:额外的参数;config:其他配置
let observable = qiniu.upload(
d.file,
key,
_this.uploadData.token,
putExtra,
config
);
let error = function (err) {
console.log("上传出错",err);
};
let complete = function (res) {
console.log(res);
_this.fileList.push({
name:res.key,
url:_this.uploadUrl+res.key
})
};
let next = function (response) {};
let subObject = {
next: next,
error: error,
complete: complete,
};
let subscription = observable.subscribe(subObject);
},
beforeMount() { this.getToken(); },