【微信小程序分包上传大文件/视频】
这不前两天来了个奇葩需求,我写的小视频平台人家要上传2个G以上的视频,一开始咋想都想不通怎么写,后来一下就茅厕顿开了属于是,话不多说直接上码!
upload.js:
var bytesPerPiece = 5 * 1024 * 1024; // 每个文件切片大小定为5MB .var nowIndex = 0;//当前片indexvar 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('/');//拆解文件urlvar fileName = arr[arr.length - 1];//获得文件名var state = false;var length = parseInt(file.size / bytesPerPiece);//总片数(取整)if (bytesPerPiece * length == file.size) {state = true}if (nowIndex < length) {var chunk = fs.readFileSync(file.url, '', nowIndex * bytesPerPiece, bytesPerPiece);//按第几片加文件长度读取片文件;// var identifier = sparkMd5.hash(uuid);console.log(chunk)try {fs.writeFileSync(//保存片文件`${wx.env.USER_DATA_PATH}/${fileName}`,//给文件一个路径chunk,'utf8')} catch (e) {console.error(e)}var obj = { chunkSize: 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 => {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:
<van-uploader file-list="{{ fileList }}" deletable="{{ true }}" compressed="{{false}}"max-size="{{3221225472}}" accept="video" bind:oversize="tooBig" bind:after-read="afterRead" max-count="1"bind:delete="delete" />
js:
先需要在页面引入上面的js,用behaviors继承;
// pages/my/add_video/add_video.jsvar uploader = require('../../../common/upload.js');Page({behaviors: [uploader],/*** 页面的初始数据*/data: {fileList: [],videoData: { value: "", state: false, emptyTip: '您还没上传视频' },timer: "",},/*** 生命周期函数--监听页面加载*/onLoad: function (options) {},afterRead(event) {wx.showLoading({title: '正在上传',mask: true})const { file } = event.detail;console.log(file);let that = this;var arr = file.url.split('/');console.log("arr", arr);this.uploader(file, parseInt(file.duration), 'success');},success(res, time) {this.data.videoData.value = JSON.stringify(res.data);console.log(res);// 上传完成需要更新 fileListvar fileList = this.data.fileList;fileList.push({ url: res.data.fileUrl, duration: time });this.setData({ fileList: fileList });wx.hideLoading();},delete(e) {let fileList = this.data.fileList;let index = e.detail.index;fileList.splice(index, 1);this.setData({fileList,})},tooBig() {wx.showToast({title: '视频大小不可以超过3G!',})},})
雷猴我是前端鸡莫西,觉得写的好的麻烦点点关注谢谢老板们~祝您新年月薪2个W写的代码没bug~
【微信小程序分包上传大文件/视频】相关推荐
- 微信小程序直接上传文件到阿里云OSS组件封装
微信小程序直接上传文件到OSS 1. 封装公共方法 在根目录utils目录新建一个upload文件夹: // utils/upload/base64.jsvar base64EncodeChars = ...
- 微信小程序上传接口php,微信小程序API 上传、下载
微信小程序API 上传.下载 wx.uploadFile(OBJECT) 将本地资源上传到开发者服务器.如页面通过 wx.chooseImage 等接口获取到一个本地资源的临时文件路径后,可通过此接口 ...
- 微信小程序头像上传(一)
记录一下自己实现微信小程序头像上传的过程. wxml部分( 用了vant组件库 ): <view class="info"><van-imageroundwidt ...
- 微信小程序实现上传视频功能(后端代码是java)
微信小程序实现上传视频功能(后端代码是java) 1.前端 wxml文件 <image bindtap="uploadVideo" length="3" ...
- 微信小程序录音上传功能
微信小程序录音上传 录音弹窗wxml代码: <!-- 录音弹窗 --> <view class="cui-record" hidden="{{isHid ...
- **微信小程序图片上传+后台PHP修改图片名称**
微信小程序图片上传+后台PHP修改图片名称 前端代码:比较随意 <view class="weui-uploader"><view class="img ...
- 微信小程序图片上传九宫格拖拽组件
微信小程序图片上传&九宫格拖拽组件 前言 图片上传加九宫格拖拽是一个比较常用的组件,常用于发帖或者评论等内容上传模块,我这篇九宫格拖拽的思路是借鉴了一款优雅的小程序拖拽排序组件实现这篇文章 实 ...
- 微信小程序:上传的图片显示旋转问题
问题? 开发中遇到微信小程序在上传照片后,会有一定概率旋转,查阅了资料之后,发现是和图片中携带的exif信息中的orientation这个参数有关. 小程序的页面实用webview渲染的,webvie ...
- vue上传大文件/视频前后端(java)代码
vue上传大文件/视频前后端(java)代码 一.上传组件 二.后端java代码 注意: 一.上传组件 <template><div><!-- 上传组件 -->&l ...
最新文章
- 福建农林大学朱方捷组招聘讲师/副教授/助理——生信分析方向
- 多线程导出大规模excel文件
- HTML表格,table,thead,tbody,tfoot,th,tr,td,的属性以及跨行,跨列
- 工业相机与民用相机的区别_工业相机和普通相机的区别详解
- 国外问答网站Quora数据的爬虫 Java
- Android 第三方
- 安装好grunt,cmd 提示grunt不是内部或外部命令 怎么办?
- Set static ip for ubuntu
- 【C++ Primer 第10章】 10.4.1 插入迭代器
- visual studio for mac在线安装网络错误
- netbeans运行KEmulator
- uni app 自定义基座 真机调试 ios设备
- java ajax传参问题
- 如何处理J-Link不能连接目标MCU的问题?
- Mac下的平铺式桌面 - Yabai
- 关于一阶线性电路的零输入响应
- QT 中怎样实现延时 stop
- leetcode Patching Array
- dos bat批处理的魅力 批处理读取文本中的每一行 操作文件
- springboot选择题、判断题