tp5+微信小程序 分片上传

代码如下

tp5端代码

/**
 * /wxapp/public/part_file
 * identifier:identifier
 * index:分块系号
 * dir:文件上传目录 用于一会合并的目录每次请求接口不一样
 */
public function part_file()
{
    $identifier = $this->request->param('identifier');
    $index      = (int)$this->request->param('index');//分块系号
    $dir        = './upload/dz17/user/' . $this->request->param('dir') . '/';//文件上传目录
    if (!is_dir($dir)) {
        @mkdir($dir);
    }
    $tmppath = $dir . $identifier . '_' . $index;
    $part    = file_get_contents('php://input');
    file_put_contents($tmppath, $part);//(缓存分块文件 )
    $this->success('上传成功!');
}

/**
 * /wxapp/public/merge_file
 * identifier:identifier
 * fileName:文件名字
 * dir:刚刚生成的唯一目录
 */
public function merge_file()
{
    $identifier = $this->request->param('identifier');
    $fileName   = $this->request->param('fileName');
    $index      = (int)$this->request->param('index');//分块数
    $dir        = './upload/dz17/user/' . $this->request->param('dir') . '/';
    $tmppath    = $dir . $fileName;
    for ($i = 0; $i < $index; $i++) {
        $path   = $dir . $identifier . '_' . $i;
        $binary = file_get_contents($path);
        $res    = file_put_contents($tmppath, $binary, FILE_APPEND);
        if ($res) {
            @unlink($path);
        }//删除缓存分块文件
    }

    $data = ['url' => substr($tmppath, 1)];

    $this->success('file', $data);//返回文件文件(此处跟据自己实际去改)
}
 

小程序端代码

<template>
  <view class="container">
    <view class="btn">
      <button @click="chooseFile">选择文件</button>
    </view>
    <view class="btn">
      <button @click="uploadPause">暂停上传</button>
    </view>
    <view class="btn">
      <button @click="uploadResume">继续上传</button>
    </view>
    <view class="btn">
      <button @click="uploadCancel">取消文件</button>
    </view>
    <view>
      <view>当前文件:{{ upload.eq }},大小:{{ upload.size }}KB</view>
      <view>上传进度:{{ upload.progress }}%</view>
      <view>已上传大小:{{ upload.uploadedSize }}KB</view>
      <view>平均速度:{{ upload.averageSpeed }}KB/s</view>
      <view>剩余时间:{{ upload.timeRemaining }}s</view>
    </view>
  </view>
</template>

<script>
import Uploader from 'miniprogram-file-uploader'
import { lt10, rndInt } from '@/utils/utils'
export default {
  data() {
    return {
      upload: {
        eq: -1,
        size: 0,
        progress: 0,
        uploadedSize: 0,
        averageSpeed: 0,
        timeRemaining: 0
      }
    }
  },
  onLoad(option) {},
  methods: {
    uploadPause() {
      this.uploader && this.uploader.pause()
    },
    uploadResume() {
      this.uploader && this.uploader.resume()
    },
    uploadCancel() {
      this.uploader && this.uploader.cancel()
    },
    uploadOne(obj, n = 0) {
      if (typeof obj[n] === 'undefined') {
        return false
      }
      var tempFilePath = obj[n].path,
        d = new Date()
      var tmpArr = tempFilePath.split('.'),
        file = {
          fileName: '',
          ext: '',
          index: 0,
          now: 0,
          chunkSize: 1024 * 1024,
          dir: ''
        }
      file.now = d.getTime() + '' + rndInt(1000, 9999)
      if (tmpArr.length > 1) {
        file.ext = tmpArr.pop().toLowerCase()
      }
      file.fileName = file.now + (file.ext !== '' ? '.' + file.ext : '')
      file.index = Math.ceil(obj[n].size / file.chunkSize)
      file.dir =
        d.getFullYear() + '' + lt10(d.getMonth() + 1) + lt10(d.getDate())
      var opt = {
        fileName: file.fileName,
        chunkSize: file.chunkSize,
        maxConcurrency: 1,
        totalSize: obj[n].size,
        query: { fid: 1, dir: file.dir },
        uploadUrl: 'https://dz17.jscxkf.com/api/wxapp/public/part_file', //分块上专
        mergeUrl:
          'https://dz17.jscxkf.com/api/wxapp/public/merge_file?fid=1&index=' +
          file.index +
          '&dir=' +
          file.dir,
        tempFilePath: tempFilePath
      }
      switch (obj[n].fileType) {
        case 'image':
          break
        case 'video':
          break
        default:
      }
      const uploader = new Uploader(opt)
      uploader.on('retry', res => {
        console.log('retry', res.url)
      })
      uploader.on('success', res => {
        this.uploadOne(obj, n + 1)
      })
      uploader.on('fail', res => {
        console.log('fail', res)
      })
      uploader.on('progress', res => {
        var tmp = {
          eq: n,
          size: obj[n].size / 2048,
          progress: res.progress,
          uploadedSize: parseInt(res.uploadedSize / 2048),
          averageSpeed: parseInt(res.averageSpeed / 2048),
          timeRemaining: res.timeRemaining / 1000
        }
        this.upload = tmp
      })
      uploader.upload()
      this.uploader = uploader
    },
    chooseFile() {
      let taht = this
      if (Uploader.isSupport()) {
        wx.chooseMessageFile({
          count: 1,
          success(res) {
            console.log(res)
            if (res.tempFiles instanceof Array && res.tempFiles.length > 0) {
              taht.uploadOne(res.tempFiles, 0)
            }
          }
        })
      } else {
        return this.$u.route('小程序版本库过低,无法上传')
      }
    }
  }
}
</script>

  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值