oss.js
2.19 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
// import { baseConfig } from '@/main'
import { fetchConfig } from '@/config'
const OSS = require('ali-oss')
export default {
/**
* 阿里云oss sdk文件上传 dir 上传到的文件位置
* @param {*} file 文件流
* @param {*} successCallback 成功回调
* @param {*} errCallBack 失败回调
* @param {*} bucketName 阿里云桶名(可以指定多个桶名)
* @param {*} dir 上传文件夹路径 譬如images
*/
async bucketUpload(file, successCallback = new Function(), errCallBack = new Function(), bucketName = 'zzl-filerepostorypublic', dir = 'image') {
const baseConfig = await fetchConfig()
console.log('baseConfig', baseConfig)
const fileName = file.name // 先获取上传要的资料签名
// 实例化一个上传客户端
const client = new OSS({
// yourRegion填写Bucket所在地域。Region填写为oss-cn-hangzhou。
// region: "oss-cn-beijing", //我的存储是北京,可根据具体配置自行修改
// region: "oss-cn-shanghai",
// 从STS服务获取的临时访问密钥(AccessKey ID和AccessKey Secret)。)(后台接口返回)
accessKeyId: baseConfig.alyOss.accessKeyId,
accessKeySecret: baseConfig.alyOss.accessKeySecret,
// 从STS服务获取的安全令牌(SecurityToken)。
// stsToken: obj.securityToken,
// 填写Bucket名称。
bucket: baseConfig.alyOss.bucket,
endpoint: baseConfig.alyOss.endpoint
})
try {
// 为保证唯一性,可以通过uuid将文件名替换
// let uuid = uuidv4() + fileName.substring(fileName.lastIndexOf('.'))if (dir.substring(dir.length - 1, 1) !== '/') {
dir += '/'
const result = client.put(dir + fileName, file)
result
.then(res => {
console.log(res, '返回文件名和文件地址')
const size = file.size > 1000000 ? parseFloat(file.size / 1000000).toFixed(2) + 'M' : parseFloat(file.size / 1000).toFixed(2) + 'KB'
successCallback({
attachment: fileName,
aliyunAddress: res.url,
size: size
})
})
.catch(err => {
errCallBack(err)
})
} catch (e) {
console.log(e)
}
}
}