在前端開發中文件上傳是常常會遇到的,而且多數狀況會使用第三方平臺來存儲文件,騰訊雲cos是咱們經常使用的。本篇文章就是帶我從前端的角度實現騰訊雲COS存儲。本文參考了騰訊雲COS開發文檔 JavaScript SDK html
下載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);
};
複製代碼
function getFileToken (Vue, fileInfo, cos, file, uploadStatusCallbalck) {
let url = process.env.VUE_APP_URL + '/file/secretid';
if (!file) return;
// 異步獲取臨時密鑰
axios
.get (url)
.then (function (res) {
if (res.data.code == 100000) {
//獲取的臨時祕鑰存儲在vuex中
Vue.$store.commit ('UPDATE_FILE_INFO', res.data.data);
uploadFile (cos, file, res.data.data, uploadStatusCallbalck);
} else {
uploadStatusCallbalck ({success: false, msg: '獲取文件祕鑰失敗!'});
}
})
.catch (function (err) {
uploadStatusCallbalck ({success: false, msg: '獲取文件祕鑰接口出錯!'});
});
}
複製代碼
/**
* @method uploadFile
* @param {object} cos
*/
function uploadFile (cos, file, signInfo, callback) {
cos.putObject (
{
Bucket: process.env.VUE_APP_BUCKET,
Region: 'ap-shanghai',
Key: signInfo.fileId,
Body: file,
onHashProgress: function (progressData) {
console.log ('校驗中', JSON.stringify (progressData));
},
onProgress: function (progressData) {
console.log ('上傳中', JSON.stringify (progressData));
},
},
function (err, data) {
if (err) {
console.log (err);
callback ({success: false, msg: '文件上傳失敗!'});
return;
}
callback ({success: true, msg: '上傳成功!', data: data, signInfo: signInfo});
}
);
}
複製代碼
騰訊雲cos文件上傳實際是分爲三步,本地表單處理文件流 => 根據文檔獲取相關參數 => 上傳文件。vue