当前位置:   article > 正文

【微信小程序】大文件分片上传到FastDFS文件服务器_微信小程序分片上传

微信小程序分片上传

1. 小程序界面:

 2. 计算文件的MD5:

 3. 上传记录:

 

4. share.js源码:

  1. const domain = require('../../utils/domain.js').domain
  2. import SparkMD5 from '../../utils/spark-md5.js'
  3. const chooseLocation = requirePlugin('chooseLocation');
  4. Page({
  5. /**
  6. * 页面的初始数据
  7. */
  8. data: {
  9. uploadTask: '',
  10. tempFiles: '',
  11. fileName: '',
  12. chunkNo: '',
  13. identifier: '',
  14. bytesPerPiece: '',
  15. index: '',
  16. percent: '',
  17. media: [],
  18. location: '',
  19. userinfo: '',
  20. labelList: [],
  21. text: '',
  22. loading_title: '',
  23. loading_icon: '',
  24. loading_show: false,
  25. type: ''
  26. },
  27. upload(){
  28. console.log("点击上传")
  29. wx.chooseMedia({
  30. count: 1,
  31. mediaType: ['image', 'video'],
  32. sourceType: ['album'],
  33. success(res){
  34. console.log(res.tempFiles[0].tempFilePath)
  35. wx.uploadFile({
  36. header: {
  37. 'alexmisko-user': wx.getStorageSync('token')
  38. },
  39. filePath: res.tempFiles[0].tempFilePath,
  40. name: 'img',
  41. url: domain + '/video/user',
  42. success(res){
  43. console.log(JSON.parse(res.data).data)
  44. }
  45. })
  46. }
  47. })
  48. },
  49. uploadChunk(){
  50. var that = this
  51. console.log('点击分片上传')
  52. wx.chooseMedia({
  53. count: 1,
  54. mediaType: ['image', 'video'],
  55. sourceType: ['album'],
  56. success(res){
  57. that.setData({
  58. thumbTempFilePath: res.tempFiles[0].thumbTempFilePath
  59. })
  60. console.log("正在计算文件的md5......")
  61. var index = 0
  62. var identifier = SparkMD5.ArrayBuffer.hash(wx.getFileSystemManager().readFileSync(res.tempFiles[0].tempFilePath, ''))
  63. that.setData({
  64. identifier: identifier
  65. })
  66. var tempFiles = res.tempFiles[0]
  67. var arr = tempFiles.tempFilePath.split('/')
  68. var fileName = arr[arr.length-1]
  69. that.setData({
  70. type: fileName.split('.')[1]
  71. })
  72. console.log(fileName)
  73. var bytesPerPiece = 8 * 1024 * 1024;
  74. var chunkNo = parseInt(tempFiles.size / bytesPerPiece)
  75. that.uploader(tempFiles, fileName, chunkNo, identifier, bytesPerPiece, index)
  76. }
  77. })
  78. },
  79. async uploader(tempFiles, fileName, chunkNo, identifier, bytesPerPiece, index){
  80. var that = this
  81. console.log("--------------------------------------------")
  82. if(index < chunkNo){
  83. var chunk = wx.getFileSystemManager().readFileSync(tempFiles.tempFilePath, '', index * bytesPerPiece, bytesPerPiece)
  84. console.log(chunk)
  85. try{
  86. wx.getFileSystemManager().writeFileSync(
  87. `${wx.env.USER_DATA_PATH}/${fileName}`,
  88. chunk,
  89. 'utf-8'
  90. )
  91. } catch(e){
  92. console.error(e)
  93. }
  94. var obj = {fileMD5: identifier, sliceNo: index + 1, totalSliceNo: chunkNo + 1}
  95. var prog = index + 1
  96. var total = chunkNo + 1
  97. console.log(prog + '/' + total, obj);
  98. // 上传之前做备份,以便断点续传
  99. that.setData({
  100. tempFiles: tempFiles,
  101. fileName: fileName,
  102. chunkNo: chunkNo,
  103. bytesPerPiece: bytesPerPiece,
  104. index: index,
  105. })
  106. console.log("正在上传......")
  107. that.data.uploadTask = wx.uploadFile({
  108. header: {
  109. 'alexmisko-user': wx.getStorageSync('token')
  110. },
  111. url: domain + '/video/chunk/user',
  112. filePath: `${wx.env.USER_DATA_PATH}/${fileName}`,
  113. name: 'file',
  114. formData: obj,
  115. success(res) {
  116. console.log(res)
  117. index ++
  118. that.uploader(tempFiles, fileName, chunkNo, identifier, bytesPerPiece, index)
  119. },
  120. fail(res) {
  121. console.log(res)
  122. }
  123. })
  124. that.data.uploadTask.onProgressUpdate((res) => {
  125. if(res.progress % 10 == 0){
  126. that.setData({
  127. percent: parseInt(res.progress / (that.data.chunkNo + 1) + index * 100 / chunkNo)
  128. })
  129. console.log('上传进度', res.progress)
  130. console.log('已经上传的数据长度', res.totalBytesSent)
  131. console.log('预期需要上传的数据总长度', res.totalBytesExpectedToSend)
  132. }
  133. })
  134. }
  135. if(index == chunkNo){
  136. var chunk = wx.getFileSystemManager().readFileSync(tempFiles.tempFilePath, '', index * bytesPerPiece, tempFiles.size - (index * bytesPerPiece))
  137. console.log(chunk)
  138. try{
  139. wx.getFileSystemManager().writeFileSync(
  140. `${wx.env.USER_DATA_PATH}/${fileName}`,
  141. chunk,
  142. 'utf8'
  143. )
  144. } catch(e){
  145. console.error(e)
  146. }
  147. var obj = {fileMD5: identifier, sliceNo: index + 1, totalSliceNo: chunkNo + 1}
  148. var prog = index + 1
  149. var total = chunkNo + 1
  150. console.log(prog + '/' + total, obj);
  151. console.log("正在上传......")
  152. wx.uploadFile({
  153. header: {
  154. 'alexmisko-user': wx.getStorageSync('token')
  155. },
  156. url: domain + '/video/chunk/user',
  157. filePath: `${wx.env.USER_DATA_PATH}/${fileName}`,
  158. name: 'file',
  159. formData: obj,
  160. success(res) {
  161. console.log(res)
  162. console.log("---------------------上传完成!---------------------")
  163. if(that.data.type == 'mp4'){
  164. console.log("开始上传缩略图")
  165. wx.uploadFile({
  166. header: {
  167. 'alexmisko-user': wx.getStorageSync('token')
  168. },
  169. filePath: that.data.thumbTempFilePath,
  170. name: 'img',
  171. url: domain + '/video/user',
  172. success(res1){
  173. console.log("缩略图地址:")
  174. var thumbUrl = JSON.parse(res1.data).data
  175. console.log(thumbUrl)
  176. console.log("视频地址:")
  177. var url = JSON.parse(res.data).data
  178. var media = {url: url, type: url.split('.')[3], digest: that.data.identifier, thumb: JSON.parse(res1.data).data}
  179. that.data.media.push(media)
  180. that.setData({
  181. percent: 100,
  182. media: that.data.media
  183. })
  184. console.log(url)
  185. return;
  186. }
  187. })
  188. }else{
  189. console.log("图片地址:")
  190. var url = JSON.parse(res.data).data
  191. var media = {url: url, type: url.split('.')[3], digest: that.data.identifier, thumb: ''}
  192. that.data.media.push(media)
  193. that.setData({
  194. percent: 100,
  195. media: that.data.media
  196. })
  197. console.log(url)
  198. return;
  199. }
  200. },
  201. fail(res) {
  202. console.log(res)
  203. }
  204. })
  205. }
  206. },
  207. cancel(){
  208. console.log('取消')
  209. this.data.uploadTask.abort()
  210. },
  211. resume(){
  212. console.log("继续")
  213. this.uploader(this.data.tempFiles, this.data.fileName, this.data.chunkNo, this.data.identifier, this.data.bytesPerPiece, this.data.index)
  214. },
  215. close(e){
  216. console.log('关闭')
  217. this.data.media.splice(e.currentTarget.dataset.id, 1)
  218. this.setData({
  219. media: this.data.media
  220. })
  221. },
  222. label(){
  223. console.log('选择标签')
  224. wx.navigateTo({
  225. url: `../label/label?labelList=${JSON.stringify(this.data.labelList)}`,
  226. })
  227. },
  228. location(){
  229. // 先获取经纬度
  230. wx.getLocation({
  231. type: 'wgs84',
  232. success (res) {
  233. // 地图选点
  234. const key = '6CFBZ-VVOWK-GIEJF-AGSB6-FFWG7-VXB3Q'; //使用在腾讯位置服务申请的key
  235. const referer = '春禾支教'; //调用插件的app的名称
  236. const location = JSON.stringify({
  237. latitude: res.latitude,
  238. longitude: res.longitude
  239. });
  240. const category = '生活服务,娱乐休闲';
  241. wx.navigateTo({
  242. url: `plugin://chooseLocation/index?key=${key}&referer=${referer}&location=${location}&category=${category}`
  243. });
  244. }
  245. })
  246. },
  247. onShow(){
  248. const location = chooseLocation.getLocation();
  249. if(location != null){
  250. console.log(location)
  251. this.setData({
  252. location: location
  253. })
  254. }
  255. const userinfo = wx.getStorageSync('userinfo')
  256. this.setData({
  257. userinfo: userinfo
  258. })
  259. },
  260. publish(){
  261. this.setData({
  262. loading_icon: 'loading',
  263. loading_show: true,
  264. loading_title: '请等待...'
  265. })
  266. var that = this
  267. console.log("发布")
  268. wx.request({
  269. method: "POST",
  270. url: domain + '/video/flow/user',
  271. header: {
  272. "alexmisko-user": wx.getStorageSync('token')
  273. },
  274. data: {
  275. description: this.data.text,
  276. mediaList: this.data.media,
  277. longitude: this.data.location.longitude,
  278. latitude: this.data.location.latitude,
  279. location: this.data.location.name,
  280. tagList: this.data.labelList
  281. },
  282. success(res){
  283. console.log(res.data)
  284. that.setData({
  285. loading_icon: '',
  286. loading_title: res.data.msg,
  287. loading_show: true
  288. })
  289. if (res.data.code == "200"){
  290. that.setData({
  291. text: '',
  292. media: [],
  293. location: '',
  294. labelList: []
  295. })
  296. }
  297. }
  298. })
  299. },
  300. textInput(e){
  301. this.setData({
  302. text: e.detail.value
  303. })
  304. }
  305. })

5. 后端Redis上传的分片记录(需要后端代码的评论获取):

 

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/盐析白兔/article/detail/170105
推荐阅读
相关标签
  

闽ICP备14008679号