js纯前端实现腾讯纯前端实现腾讯cos文件上传功能的示例代码文件上传功能的示例代码
前言前言
在前端开发中文件上传是经常会遇到的,并且多数情况会使用第三方平台来存储文件,腾讯云cos是我们常用的。本篇文章就
是带我从前端的角度实现腾讯云COS存储。本文参考了腾讯云COS开发文档 JavaScript SDK
步骤步骤
安装腾讯云COS上传所需的sdk
下载cos-js-sdk-v5.min.js并引入index.html
监听文件上传组件
//监听文件变化
document.getElementById('file').onchange = function() {
let file = this.files[0];
let type = file.type
//初始化文件上传
initUploadObj(that, file.name, file, 'image', function(res) {
if (res.success) {
that.$message.success(res.msg)
} else {
that.$message.warning(res.msg)
}
})
}
初始化文件上传对象(封装起来其他地方上传也可以用)
/**
* 初始化上传文件对象
* @param {object} Vue
* @param {string} fileName 文件名
* @param {object} file 上传的文件流及文件类型 名称相关信息
* @param {Array} 允许上传的文件类型
* @param {function} uploadStatusCallbalck
* @return {function} 返回回调函数
*/
export const initUploadObj = function (Vue,fileName,file,type,uploadStatusCallbalck) {
let fileInfo = {
file_name: fileName,
media_type: 2,
media_sub_type: 0,
size_of_bytes: 122,
file_expired_type: 'permanent',
};
//前端做文件类型限制
if(type == 'image'){
type = ['.jpg','.gif','.jpeg','.bmp','.png'] }
if(type == 'excel'){
type = ['.xlsx'] }
let fileType =file.name ? file.name.substring(file.name.lastIndexOf(".")).toLowerCase() : '';
if (!!type && type.indexOf (fileType) < 0) {
uploadStatusCallbalck ({success: false, msg: '请上传正确的'+type+'文件格式!'});
return;
}
var cos = new COS ({
getAuthorization: function (options, callback) {
let singleInfo = Vue.$store.state.fileToken;
callback ({
TmpSecretId: singleInfo.tmpSecretId,
TmpSecretKey: singleInfo.tmpSecretKey,
XCosSecurityToken: singleInfo.sessionToken,
ExpiredTime: singleInfo.expiredTime,
});
},
});
fileInfo.file_name = file.name;
//获取文件上传密钥
getFileToken (Vue, fileInfo, cos, file, uploadStatusCallbalck);
};
获取文件上传密钥(最好存在后端通过ajax请求获取,安全性较高)
评论0