oss对象存储,申请账号,建里属于你自己的第一个Bucket,然后,你就可以为所欲为了?
也许是的,但对于H5 还不行
1.首先,安装oss
cnpm install ali-oss -D
引入 oss
const OSS = require('ali-oss');
2.你要有一个后台服务,获取ossToken等上传阿里云的必要参数
因为我是一个纯前端,对Java不甚了解,只能一笔带过了,不好意思啊,相信这点是不会难倒各位大佬的 ,
服务端签名直传oss官方文档
//获取后台签名
const URL = '/****/ossInfo' //后台提供的获取oss参数接口
export function getOsskey() {
let _this = this
return new Promise((resolve, reject) => {
//获取后台签名
http.post(URL,{}).then(result => {
sessionStorage.setItem('osskey', JSON.stringify(result.data.respData))
resolve(result.data.respData)
//需要返回5个必要参数
//region 云服务所在的地区如深圳 oss-cn-shenzhen
//bucket bucket 的名字如 test123-images
//accessKeyId 你的accessKeyId
//accessKeySecret 你的accessKeySecret
//stsToken 后台根据规则生成的签名字符串
}).catch(e => {
reject(e)
})
})
}
new 一个 oss 并上传
const client = new OSS({
region: osskey.endpoint.split('//')[1].split('.')[0],
//region: 'oss-cn-hangzhou',
bucket: osskey.bucket,
accessKeyId: osskey.accessKeyId,
accessKeySecret: osskey.accessKeySecret,
stsToken: osskey.securityToken,
})
var reader = new FileReader();
reader.readAsArrayBuffer(file);
reader.onload = function(event) {
//图片命名规则 --parth:oss存放文件路径
let storeAs = parth + Math.round(new Date().getTime() / 1000) + Math.ceil(Math.random() * 100000).toString() + '-' + random_string(32) + '.' + file.type.split('\/')[1]
//console.log(storeAs);
var buffer = new OSS.Buffer(event.target.result);
client.put(storeAs, buffer).then(function(r1) {
//console.log('put success', r1);
//返回上传后的回参
res.data = r1
return client.get(storeAs);
}).then(function(r2) {
//console.log('put success', res.data.name);
//console.log('put success', res.data.name);
// console.log(258,r2.res.data)
var uint8 = new Uint8Array(r2.res.data);
var buffer = uint8.buffer;
var file = new Blob([buffer]);
res.file = file;
readBlobAsDataURL(file, function(baseUrl) {
// console.log(456789,baseUrl);
//返回前端需要显示的url
res.baseUrl = baseUrl;
resolve(res)
});
})
}).catch(function(err) {
reject(err)
//console.error('error: %j', err);
})
}
//blob 转 baseUrl
export function readBlobAsDataURL(blob, callback) {
var a = new FileReader();
a.onload = function(e) {
callback(e.target.result);
};
a.readAsDataURL(blob);
}
页面使用
import {uploadImgs} from "../../assets/js/uploadImage";
collectFace(e) {
//图片上传oss
uploadImgs(e.target.files[0], "JSLIFE/FACE/").then(res => {
console.log(123, res)
})
},
import http from '../../services/getData'
const URL = '/*****/upload/ossInfo'
const completeUrl = '/*****/upload/getUrlByObjKey'
const OSS = require('ali-oss');
//blob 转 baseUrl
export function readBlobAsDataURL(blob, callback) {
var a = new FileReader();
a.onload = function(e) {
callback(e.target.result);
};
a.readAsDataURL(blob);
}
//32位 以内 随机码
export function random_string(len) {
len = len || 32;
var chars = 'ABCDEFGHJKMNPQRSTWXYZabcdefhijkmnprstwxyz2345678';
var maxPos = chars.length;
var pwd = '';
for(let i = 0; i < len; i++) {
pwd += chars.charAt(Math.floor(Math.random() * maxPos));
}
return pwd;
}
//获取oss图片完整路径
export function getOssUrl(keyName) {
let _this = this
return new Promise((resolve, reject) => {
//获取后台签名
//var res = {};
http.post(completeUrl,{objectKey:keyName}).then(res => {
// console.log(456,res)
resolve(res.data)
}).catch(e => {
reject(e)
})
})
}
//获取后台签名
export function getOsskey() {
let _this = this
return new Promise((resolve, reject) => {
//获取后台签名
http.post(URL,{}).then(result => {
sessionStorage.setItem('osskey', JSON.stringify(result.data.respData))
resolve(result.data.respData)
}).catch(e => {
reject(e)
})
})
}
export function isKey() {
let _this = this;
return new Promise((resolve, reject) => {
let osskey = JSON.parse(sessionStorage.getItem("osskey"))
if(!osskey) {
getOsskey().then(res => {
resolve(res)
})
} else {
//验证token是否过期
let t1 = new Date(osskey.expiration).getTime()
let t2 = new Date().getTime()
let t3 = new Date().getTime() + 3500000
if(osskey.accessKeyId && osskey.accessKeySecret && (t1 - t2) > 0 && (t1 - t3) < 0) {
resolve(osskey)
} else {
getOsskey().then(res => {
resolve(res)
})
}
}
})
}
//上传图片
export function uploadImgs(file, parth) {
let _this = this;
return new Promise((resolve, reject) => {
isKey().then(osskey => {
var res = {};
// console.log(77, osskey)
//oss 对象
//alert(3)
const client = new OSS({
region: osskey.endpoint.split('//')[1].split('.')[0],
//region: 'oss-cn-hangzhou',
bucket: osskey.bucket,
accessKeyId: osskey.accessKeyId,
accessKeySecret: osskey.accessKeySecret,
stsToken: osskey.securityToken,
})
var reader = new FileReader();
reader.readAsArrayBuffer(file);
reader.onload = function(event) {
//图片命名规则 --parth:oss存放文件路径
let storeAs = parth + Math.round(new Date().getTime() / 1000) + Math.ceil(Math.random() * 100000).toString() + '-' + random_string(32) + '.' + file.type.split('\/')[1]
//console.log(storeAs);
var buffer = new OSS.Buffer(event.target.result);
client.put(storeAs, buffer).then(function(r1) {
//console.log('put success', r1);
//返回上传后的回参
res.data = r1
return client.get(storeAs);
}).then(function(r2) {
//console.log('put success', res.data.name);
getOssUrl(res.data.name).then(result=>{
//console.log(result,result)
res.fullBaseUrl = result.respData
// console.log(r2.res.data,r2.res.data)
var uint8 = new Uint8Array(r2.res.data);
var buffer = uint8.buffer;
var file = new Blob([buffer]);
res.file = file;
readBlobAsDataURL(file, function(baseUrl) {
// console.log("baseUrl:",baseUrl);
//返回前端需要显示的url
res.baseUrl = baseUrl;
resolve(res)
});
})
}).catch(function(err) {
reject(err)
//console.error('error: %j', err);
})
}
})
})
}
//oss获取图片流并转换baseUrl
export async function getImages(url) {
let _this = this;
let imgUrl= '';
return new Promise((resolve, reject) => {
if(!url){
resolve()
}
isKey().then(osskey => {
const client = new OSS.Wrapper({
region: osskey.endpoint.split('//')[1].split('.')[0],
//region: 'oss-cn-hangzhou',
bucket: osskey.bucket,
accessKeyId: osskey.accessKeyId,
accessKeySecret: osskey.accessKeySecret,
stsToken: osskey.securityToken,
})
client.get(url)
.then(function(r2) {
var uint8 = new Uint8Array(r2.res.data);
var buffer = uint8.buffer;
var file = new Blob([buffer]);
readBlobAsDataURL(file, function(baseUrl) {
//返回前端需要显示的url
resolve(baseUrl)
});
}).catch(e=>{
reject(e)
})
})
})
}
//获取照片
changeImg(e) {
let _this = this;
// console.log(e.target.files);
var fileObj = e.target.files[0];
// console.log(fileObj);
var type = fileObj.type.split('/')[0];
if (type != 'image') {
this.$message({
type: 'error',
message: '请上传图片'
});
return;
}
this.fileObj = fileObj;
uploadImgs(this.fileObj, "JSLIFE/FACE/").then(res => {
console.log(123, res)
this.faceImg = success;
this.resTxt = '采集成功';
this.iscollect = false;
})
}