【微信小程序分包上传大文件/视频】 |
您所在的位置:网站首页 › 文件上传程序怎么弄 › 【微信小程序分包上传大文件/视频】 |
这不前两天来了个奇葩需求,我写的小视频平台人家要上传2个G以上的视频,一开始咋想都想不通怎么写,后来一下就茅厕顿开了属于是,话不多说直接上码! upload.js: var bytesPerPiece = 5 * 1024 * 1024; // 每个文件切片大小定为5MB . var nowIndex = 0;//当前片index var identifier = `${Date.now()}${Math.random()}`;//文件唯一标识 var array = identifier.split('.');//处理唯一标识 identifier = array[0].toString() + array[1].toString(); const fs = wx.getFileSystemManager(); module.exports = Behavior({ data: { bytesPerPiece: 20 * 1024 * 1024, // 每个文件切片大小定为1MB . totalPieces: 0, }, methods: { onLoad: function (obj) { }, async uploader(file, time, success_func) { var arr = file.url.split('/');//拆解文件url var fileName = arr[arr.length - 1];//获得文件名 var state = false; var length = parseInt(file.size / bytesPerPiece);//总片数(取整) if (bytesPerPiece * length == file.size) { state = true } if (nowIndex { nowIndex++; this.uploader(file, time, success_func); }, fail: res => { console.log(res); } }) } if (nowIndex == length && !state) {//当index等于分片长度时上传剩余部分 var chunk = fs.readFileSync(file.url, '', nowIndex * bytesPerPiece, file.size - (nowIndex * bytesPerPiece));//按第几片加文件长度读取片文件; console.log('upload7', chunk) try { fs.writeFileSync(//保存片文件 `${wx.env.USER_DATA_PATH}/${fileName}`, chunk, 'utf8' ) } catch (e) { console.error(e) } var obj = { chunkSize: file.size - (nowIndex * bytesPerPiece), fileName: fileName, identifier: identifier, index: nowIndex, totalChunks: state ? length : length + 1, totalSize: file.size } console.log(nowIndex, obj); await wx.uploadFile({ url: this.data.host + '/apiToker/tkFile/base/burstUpload', // url: args.url, header: { // method: 'GET', Authorization: wx.getStorageSync('Authorization'), }, filePath: `${wx.env.USER_DATA_PATH}/${fileName}`, name: 'file', // header: {}, formData: obj, success: res => { console.log(res); this.request({ url: this.data.host + '/apiToker/tkFile/base/mergeShard', data: { identifier: identifier, fileName: fileName }, method: 'POST' }, res => { this[success_func](res, time); }) } }) } } } })你需要上传视频的页面需要引入vant的van-uploader组件 wxml: |
今日新闻 |
推荐新闻 |
CopyRight 2018-2019 办公设备维修网 版权所有 豫ICP备15022753号-3 |