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

1. 小程序界面:

 2. 计算文件的MD5:

 3. 上传记录:

 

4. share.js源码:

const domain = require('../../utils/domain.js').domain
import SparkMD5 from '../../utils/spark-md5.js'
const chooseLocation = requirePlugin('chooseLocation');
Page({

  /**
   * 页面的初始数据
   */
  data: {
    uploadTask: '',
    tempFiles: '',
    fileName: '', 
    chunkNo: '', 
    identifier: '', 
    bytesPerPiece: '',
    index: '',
    percent: '',
    media: [],
    location: '',
    userinfo: '',
    labelList: [],
    text: '',
    loading_title: '',
    loading_icon: '',
    loading_show: false,
    type: ''
  },
  upload(){
    console.log("点击上传")
    wx.chooseMedia({
      count: 1,
      mediaType: ['image', 'video'],
      sourceType: ['album'],
      success(res){
        console.log(res.tempFiles[0].tempFilePath)
        wx.uploadFile({
          header: {
            'alexmisko-user': wx.getStorageSync('token')
          },
          filePath: res.tempFiles[0].tempFilePath,
          name: 'img',
          url: domain + '/video/user',
          success(res){
            console.log(JSON.parse(res.data).data)
          }
        })
      }
    })
  },

  uploadChunk(){
    var that = this
    console.log('点击分片上传')
    wx.chooseMedia({
      count: 1,
      mediaType: ['image', 'video'],
      sourceType: ['album'],
      success(res){
        that.setData({
          thumbTempFilePath: res.tempFiles[0].thumbTempFilePath
        })
        console.log("正在计算文件的md5......")
        var index = 0
        var identifier = SparkMD5.ArrayBuffer.hash(wx.getFileSystemManager().readFileSync(res.tempFiles[0].tempFilePath, ''))
        that.setData({
          identifier: identifier
        })
        var tempFiles = res.tempFiles[0]
        var arr = tempFiles.tempFilePath.split('/')
        var fileName = arr[arr.length-1]
        that.setData({
          type: fileName.split('.')[1]
        })
        console.log(fileName)
        var bytesPerPiece = 8 * 1024 * 1024;
        var chunkNo = parseInt(tempFiles.size / bytesPerPiece)
        that.uploader(tempFiles, fileName, chunkNo, identifier, bytesPerPiece, index)
      }
    })
  },

  async uploader(tempFiles, fileName, chunkNo, identifier, bytesPerPiece, index){
    var that = this
    console.log("--------------------------------------------")

    if(index < chunkNo){
      var chunk = wx.getFileSystemManager().readFileSync(tempFiles.tempFilePath, '', index * bytesPerPiece, bytesPerPiece)
      console.log(chunk)
      try{
        wx.getFileSystemManager().writeFileSync(
          `${wx.env.USER_DATA_PATH}/${fileName}`,
          chunk,
          'utf-8'
        )
      } catch(e){
        console.error(e)
      }
      var obj = {fileMD5: identifier, sliceNo: index + 1, totalSliceNo: chunkNo + 1}
      var prog = index + 1
      var total = chunkNo + 1
      console.log(prog + '/' + total, obj);
      // 上传之前做备份,以便断点续传
      that.setData({
        tempFiles: tempFiles,
        fileName: fileName, 
        chunkNo: chunkNo, 
        bytesPerPiece: bytesPerPiece, 
        index: index,
      })
      console.log("正在上传......")
      that.data.uploadTask = wx.uploadFile({
        header: {
          'alexmisko-user': wx.getStorageSync('token')
        },
        url: domain + '/video/chunk/user',
        filePath: `${wx.env.USER_DATA_PATH}/${fileName}`,
        name: 'file',
        formData: obj,
        success(res) {
          console.log(res)
          index ++
          that.uploader(tempFiles, fileName, chunkNo, identifier, bytesPerPiece, index)
        },
        fail(res) {
          console.log(res)
        }
      })
      that.data.uploadTask.onProgressUpdate((res) => {
        if(res.progress % 10 == 0){
          that.setData({
            percent: parseInt(res.progress / (that.data.chunkNo + 1) + index * 100 / chunkNo)
          })
          console.log('上传进度', res.progress)
          console.log('已经上传的数据长度', res.totalBytesSent)
          console.log('预期需要上传的数据总长度', res.totalBytesExpectedToSend)
        }
      })
    }
    if(index == chunkNo){
      var chunk = wx.getFileSystemManager().readFileSync(tempFiles.tempFilePath, '', index * bytesPerPiece, tempFiles.size - (index * bytesPerPiece))
      console.log(chunk)
      try{
        wx.getFileSystemManager().writeFileSync(
          `${wx.env.USER_DATA_PATH}/${fileName}`,
          chunk,
          'utf8'
        )
      } catch(e){
        console.error(e)
      }
      var obj = {fileMD5: identifier, sliceNo: index + 1, totalSliceNo: chunkNo + 1}
      var prog = index + 1
      var total = chunkNo + 1
      console.log(prog + '/' + total, obj);
      console.log("正在上传......")
      wx.uploadFile({
        header: {
          'alexmisko-user': wx.getStorageSync('token')
        },
        url: domain + '/video/chunk/user',
        filePath: `${wx.env.USER_DATA_PATH}/${fileName}`,
        name: 'file',
        formData: obj,
        success(res) {
          console.log(res)
          console.log("---------------------上传完成!---------------------")
          if(that.data.type == 'mp4'){
            console.log("开始上传缩略图")
            wx.uploadFile({
              header: {
                'alexmisko-user': wx.getStorageSync('token')
              },
              filePath: that.data.thumbTempFilePath,
              name: 'img',
              url: domain + '/video/user',
              success(res1){
                console.log("缩略图地址:")
                var thumbUrl = JSON.parse(res1.data).data
                console.log(thumbUrl)
                console.log("视频地址:")
                var url = JSON.parse(res.data).data
                var media = {url: url, type: url.split('.')[3], digest: that.data.identifier, thumb: JSON.parse(res1.data).data}
                that.data.media.push(media)
                that.setData({
                  percent: 100,
                  media: that.data.media
                })
                console.log(url)
                return;
              }
            })
          }else{
            console.log("图片地址:")
            var url = JSON.parse(res.data).data
            var media = {url: url, type: url.split('.')[3], digest: that.data.identifier, thumb: ''}
            that.data.media.push(media)
            that.setData({
              percent: 100,
              media: that.data.media
            })
            console.log(url)
            return;
          }
        },
        fail(res) {
          console.log(res)
        }
      })
    }
  },

  cancel(){
    console.log('取消') 
    this.data.uploadTask.abort()
  },

  resume(){
    console.log("继续")
    this.uploader(this.data.tempFiles, this.data.fileName, this.data.chunkNo, this.data.identifier, this.data.bytesPerPiece, this.data.index)
  },

  close(e){
    console.log('关闭')
    this.data.media.splice(e.currentTarget.dataset.id, 1)
    this.setData({
      media: this.data.media
    })
  },
  
  label(){
    console.log('选择标签')
    wx.navigateTo({
      url: `../label/label?labelList=${JSON.stringify(this.data.labelList)}`,
    })
  },

  location(){
    // 先获取经纬度
    wx.getLocation({
     type: 'wgs84',
     success (res) {
        // 地图选点
        const key = '6CFBZ-VVOWK-GIEJF-AGSB6-FFWG7-VXB3Q'; //使用在腾讯位置服务申请的key
        const referer = '春禾支教'; //调用插件的app的名称
        const location = JSON.stringify({
          latitude: res.latitude,
          longitude: res.longitude
        });
        const category = '生活服务,娱乐休闲';
        wx.navigateTo({
          url: `plugin://chooseLocation/index?key=${key}&referer=${referer}&location=${location}&category=${category}`
        });
      }
    })
  },

  onShow(){
    const location = chooseLocation.getLocation();
    if(location != null){
      console.log(location)
      this.setData({
        location: location
      })
    }
    const userinfo = wx.getStorageSync('userinfo')
    this.setData({
      userinfo: userinfo
    })
  },

  publish(){
    this.setData({
      loading_icon: 'loading',
      loading_show: true,
      loading_title: '请等待...'
    })
    var that = this
    console.log("发布")
    wx.request({
      method: "POST",
      url: domain + '/video/flow/user',
      header: {
        "alexmisko-user": wx.getStorageSync('token')
      },
      data: {
        description: this.data.text,
        mediaList: this.data.media,
        longitude: this.data.location.longitude,
        latitude: this.data.location.latitude,
        location: this.data.location.name,
        tagList: this.data.labelList
      },
      success(res){
        console.log(res.data)
        that.setData({
          loading_icon: '',
          loading_title: res.data.msg,
          loading_show: true
        })
        if (res.data.code == "200"){
          that.setData({
            text: '',
            media: [],
            location: '',
            labelList: []
          })
        }
      }
    })
  },

  textInput(e){
    this.setData({
      text: e.detail.value
    })
  }
})

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

 

  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 14
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 14
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值