下载ali-oss
npm install ali-oss --save
引入
const OSS = require("ali-oss");
//这些都是后台给的 包括 阿里云的地址 id 密码 名称
const client = new OSS({
region: '<oss region>',
endpoint: "",
accessKeyId: '<Your accessKeyId>',
accessKeySecret: '<Your accessKeySecret>',
bucket: '<Your bucket name>'
});
//假如是base64编码
this.redisImg= "data:image/png;base64,s4c6QAAx1W+T2NAAAAAElFTkSuQmCC";
//上传base64图片到阿里云
updateOss() {
// base64转blob
const blob = dataURLtoBlob(this.redisImg);
// blob转arrayBuffer
const reader = new FileReader();
reader.readAsArrayBuffer(blob);
reader.onload = event => {
// arrayBuffer转Buffer
const buffer = toBuffer(event.target.result);
//命名规则 以后缀为文件目录 md5为文件名 可自定义
//${this.suffix}/${this.pw}.${this.suffix}
client
.put(`${this.suffix}/${this.pw}.${this.suffix}`, buffer)
.then(res => {
console.log(res);
})
.catch(err => {
console.log(err);
});
};
},
//上传本地文件
ajax(url, callback, options) {
window.URL = window.URL || window.webkitURL;
var xhr = new XMLHttpRequest();
xhr.open("get", url, true);
if (options.responseType) {
xhr.responseType = options.responseType;
}
xhr.onreadystatechange = function() {
if (xhr.readyState === 4 && xhr.status === 200) {
callback(xhr);
}
};
xhr.send();
},
//上传项目内文件到阿里云
updateModel() {
//要上传的文件
let url = "./model.obj";
this.ajax(
url,
xhr => {
var blob = new Blob([xhr.response]);
// blob转arrayBuffer
const reader = new FileReader();
reader.readAsArrayBuffer(blob);
reader.onload = event => {
// arrayBuffer转Buffer
const buffer = toBuffer(event.target.result);
client
.put(`obj/${this.pw}.obj`, buffer)
.then(res => {
console.log(res.url);//文件在阿里云路径,不能在地址栏访问
let signUrl = client.signatureUrl(res.name, {expires: 3600});
console.log(signUrl);//文件可以在地址栏访问
//把生成的阿里云地址保存起来
this.$store.dispatch("getObjUrl", res.url);
})
.catch(err => {
console.log(err);
});
};
},
{
responseType: "blob"
}
);
}
// base64转blob
dataURLtoBlob(dataurl) {
var arr = dataurl.split(','),
mime = arr[0].match(/:(.*?);/)[1],
bstr = atob(arr[1]),
n = bstr.length,
u8arr = new Uint8Array(n);
while (n--) {
u8arr[n] = bstr.charCodeAt(n);
}
return new Blob([u8arr], { type: mime });
},
//ArrayBuffer ---> Buffer
toBuffer(ab) {
var buf = new Buffer(ab.byteLength);
var view = new Uint8Array(ab);
for (var i = 0; i < buf.length; ++i) {
buf[i] = view[i];
}
return buf;
}