1.安装ali-oss
npm install ali-oss
- 引入ali-oss
let OSS = require('ali-oss');
3.upload组件上传两种方式
*注:阿里云服务器需配置跨域, API为后台获取签名接口
//分片上传
imgChange (file, fileList) {
let that = this
let storeAs = 'upload-file' + '/' + file.name
OSS.urllib.request("API", { method: 'GET' }, (err, response) => {
if (err) {
return alert(err);
}
let result = JSON.parse(response);
let client = new OSS({
accessKeyId: result.data.accessKeyId,
accessKeySecret: result.data.accessKeySecret,
stsToken: result.data.securityToken,
// region表示您申请OSS服务所在的地域,例如oss-cn-hangzhou。
// bucket文件保存路径
region: 'oss-cn-chengdu',
bucket: 'liangchuang'
});
// storeAs可以自定义为文件名(例如file.txt)或目录(例如abc/test/file.txt)的形式,实现将文件上传至当前Bucket或Bucket下的指定目录。
// file可以自定义为File对象、Blob数据以及OSS Buffer。
// 注意上传的内容是file.raw,不是file
client.multipartUpload(storeAs, file.raw).then(function (result) {
let url = result.res.requestUrls[0]
let str = url.substr(0, url.indexOf("?"))
that.ruleForm.src = str
if (that.ruleForm.type == 1) {
that.ruleForm.imageUrl = str
} else {
that.ruleForm.videoUrl = str
}
}).catch(function (err) {
console.log(err);
});
});
},
function upload (file, type, size = 300) {
let that = this
if (file.size > 1024 * size) {
Message({
message: '图片大小不能超过' + size + 'KB,请重新上传',
type: 'error',
offset: 500
})
return ''
}
return new Promise((resolve, reject) => {
var point = file.raw.name.lastIndexOf(".");
OSS.urllib.request("API", { method: 'GET' }, (err, response) => {//获取配置信息
if (err) {
return alert(err);
}
let result = JSON.parse(response);//获取配置
var name = file.raw.name.substr(point);
let cdnDomain = result.data.cdnDomain
let storeAs = result.data.path + '/' + Date.parse(new Date()) + name// 根据type和moduleId拼接目录和文件名
let client = new OSS({// 阿里云oss配置信息
accessKeyId: result.data.accessKeyId,
accessKeySecret: result.data.accessKeySecret,
stsToken: result.data.securityToken,
region: 'oss-cn-chengdu',
bucket: result.data.bucketName
});
async function putObject () {
try {
let result = await client.put(storeAs, file.raw);
result.cdnDomain = cdnDomain
resolve(result);
} catch (e) {
}
}
putObject();
});
})
}