用uniapp開發APP上傳視頻文件,大文件可以上傳成功,但是一旦打包為H5的代碼,就會一提示鏈接超時,我的代碼中是實現的上傳到阿里云
如果需要看全文的私信我
官方開發文檔地址
前端:使用分片上傳的方式上傳大文件_對象存儲(OSS)-阿里云幫助中心
找到javaScript示例,我是在這個基礎上改寫為uniapp可用的
服務端獲取STS安全令牌等
使用STS臨時訪問憑證訪問OSS_對象存儲(OSS)-阿里云幫助中心
uniapp實現代碼
注意:H5上傳在界面上引用oss組件
//阿里云:H5分片上傳//#ifdef H5import OSS from 'ali-oss';// #endif
ali-oss安裝命令:npm i ali-oss
1、在界面上寫個操作事件,調用方法:chooseFile()選擇相冊文件(用uni.chooseVideo還是uni.chooseFile根據需求改寫)
chooseFile() {uni.chooseVideo({sourceType: ['album'], // ['album', 'camera'],count: 999,compressed: false,maxDuration: 60,camera: 'back',success: async(res) => {// #ifdef H5const sizeInBytes = res.size;const sizeInMB = sizeInBytes / (1024 * 1024);if (sizeInMB.toFixed(2) > 2) { //大于100MB采用分片上傳that.chooseAndUploadVideo(res)} else { //普通上傳}// #endif})}
2、大于100mb采用分片上傳。分片上傳方法:chooseAndUploadVideo()
async chooseAndUploadVideo(res) {var that = thisthat.showBackCover = true; // 打開遮罩層uni.showLoading({title: that.$t('cloneindex.addclone_uploading')})const filePath = res.tempFilePath;const fileNameTemp = filePath.substring(filePath.lastIndexOf('/') + 1);var fileH5Name = ""fileH5Name = res.namevar fileH5NameStr = fileH5Name.split(".")var lengthName = fileH5NameStr.length - 1//上傳文件的后綴var lastName = "." + fileH5NameStr[lengthName]//根據選擇文件的后綴重命名let fileName = 's' + that.random_string(6) + '_' + new Date().getTime() + lastName;try {const result = await this.uploadFile(fileName, filePath);} catch (err) {console.error('分片上傳失敗:', err);}},
3、分片上傳方法:uploadFile()
async uploadFile(name, filePath) {var that = thisconst params = {sourceType: "2.1",userId: this.userInfo.userId}//調用服務端接口獲取sts憑證const response = await getStsACS({params});name = response.keyPrefix ? response.keyPrefix + name : nameconst client = new OSS({region: response.region ? response.region : 'oss-cn-shanghai', // 替換為你的實際區域accessKeyId: response.AccessKeyId, // 替換為你的實際 AccessKeyIdaccessKeySecret: response.AccessKeySecret, // 替換為你的實際 AccessKeySecretstsToken: response.SecurityToken, // 替換為你的實際 SecurityTokenbucket: response.bucket ? response.bucket :'wakebaoai', // 替換為你的實際存儲空間名稱oss-cn-shanghai.aliyuncs.com});const file = await this.getFileFromPath(filePath);const options = {progress: (p) => {},parallel: 4,partSize: 1024 * 1024,mime: 'video/mp4',};// 分片上傳await client.multipartUpload(name, file, options);uni.hideLoading()that.aliUrl = response.url ? response.url : that.aliUrl//上傳成功后:文件地址var savePath = that.aliUrl + "/" + name;},
根據以上代碼,整合到你的項目里就可以實現分片上傳