文件上传Oss
——纯前端(2)
兄弟篇:
文件上传Oss——纯前端(1)(小白笔记)
文件上传Oss——前、后端结合(基于Springboot)(小白笔记)
采用分片式上传,封装成oss.js
工具类,方便调用
oss.js
工具类
import OSS from 'ali-oss'
const region = 'oss-cn-beijing'
const accessKeyId = 'LT********o4'
const accessKeySecret = '6vVU******************Mjkv'
const bucket = 'bucket名'
const path = '存储路径,默认根目录'
let client = new OSS({
region: region,
accessKeyId: accessKeyId,
accessKeySecret: accessKeySecret,
bucket: bucket,
path: path
})
// 上传
const CooOss = function(file) {
if (this instanceof CooOss) {
let objectKey = file.lastModified + '_' + file.name
return new Promise((resolve, reject) => {
client
.multipartUpload(objectKey, file)
.then((result) => {
console.log(result)
resolve({
code: 0,
objectKey: objectKey,
url: this.getOssFileUrl(objectKey),
msg: 'ok'
})
})
.catch((err) => {
console(err)
console.error('上传出错了')
reject({ code: -1, url: '', objectKey: '', msg: '上传出错了' })
})
})
} else {
return new CooOss(file)
}
}
/**
*
* @param {上传是设置文件key 一般是文件名} obecjtKey
*/
CooOss.prototype.getOssFileUrl = (obecjtKey) => {
if (!obecjtKey) return new Error('object key 必须传')
return 'https://' + bucket + '.' + region + '.aliyuncs.com/' + obecjtKey
}
export default {
install(Vue) {
Vue.prototype.Oss = {
uploadFile: CooOss,
}
}
}
mian.js
调用
import Oss from './utils/oss'
Vue.use(Oss)
页面调用(支持多选)
<v-file-input chip show-size counter multiple accept="image/*" label="File input" :value="files" v-model="files"></v-file-input>
<v-btn small style="margin-left: 16px" @click="uploadFile(files)">上传</v-btn>
uploadFile(files) {
for (let index = 0; index < files.length; index++) {
const f = files[index]
this.Oss.uploadFile(f).then((res) => {
console.log(res)
})
}
this.files = []
alert('上传成功')
},
谢谢,欢迎留言交流