分类目录: html5
前端上传文件到OSS
Post date:
Author: cyy
Number of comments: no comments
前端上传文件到OSS
有许多业务需要前端单独上传文件到OSS上,下面提供一个现成的方法。
- 第一步,先引入oss的sdk
<script src="https://gosspublic.alicdn.com/aliyun-oss-sdk-4.4.4.min.js"></script>
- 第二步,创建一个uploader.js
- 注:需要后端提供STS签名
function AliyunOSS () {
}
AliyunOSS.prototype.getUFileToken = function (options, success, error) {
axios({
method: 'get',
url: api_host + '/api/oss-token',
data: {},
}).then(data => {
success(data.data);
}).catch(error)
}
AliyunOSS.prototype.uploadFile = function (options, success, error, progresss) {
let file = options.file || {};
let fileName = file.name;
this.getUFileToken({}, function (token) {
let client = new OSS.Wrapper({
accessKeyId: token.AccessKeyId,
accessKeySecret: token.AccessKeySecret,
stsToken: token.SecurityToken,
endpoint: 'https://' + token.Endpoint,
bucket: token.Bucket
});
client.multipartUpload(fileName, file,
{
mime: file.type,
progress: async function progress (p, checkpoint) {
progresss(p);
}
}).then(result => {
// 上传成功
success({
msg: "",
path: 'https://test.tootootool.com' + '/' + fileName,
file: file
});
}).catch(function (err) {
error({ msg: err, file: file });
});
}, error);
}
- 第三步,引用js
<script src="https://gosspublic.alicdn.com/aliyun-oss-sdk-4.4.4.min.js"></script>
<script src="../../../common/utils/uploader.js"></script>
- 第四步,使用
<input type="file" @change="onFileChange">
data: function () {
return {
uFile: null, // oss容器
}
},
methods: {
// 文件上传
onFileChange ($event) {
let this_= this;
let files = $event.target.files || $event.dataTransfer.files;
if (files) {
// 调用oss上传
if (!this_.uFile) {
this_.uFile = new AliyunOSS();
}
this_.uFile.uploadFile({ file: files[0] }, function (res) {
console.log('上传成功-->>', res.path)
}, function (error) {
console.error('err', error)
}, (progress) {
let progress = Math.round(progress * 100) + '%';
console.log('上传进度-->>', progress)
});
}
}
}
完成!