用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;},
根据以上代码,整合到你的项目里就可以实现分片上传