• 欢迎访问搞代码网站,推荐使用最新版火狐浏览器和Chrome浏览器访问本网站!
  • 如果您觉得本站非常有看点,那么赶紧使用Ctrl+D 收藏搞代码吧

.NET或.NET Core Web APi基于tus协议实现断点续传的示例

c# 搞代码 4年前 (2022-01-09) 11次浏览 已收录 0个评论

前言

前两天我采用技巧式方案基本实现大文件分片上传,这里只是重点在于个人思路和亲身实践,若在实际生产环境要求比较高的话肯定不行,仍存在一些问题需要深入处理,本文继续在之前基础上给出基于tus协议的轮子方案,本打算再次尝试利用.NET Core实现此协议,但在github上一搜索早在2016年就已有此协议对应的.NET和.NET Core方案,并且一直更新到最近的.NET Core 3.x版本,完全满足各位所需,本文是我写出的一点demo,demo地址:https://github.com/wangpengxpy/tus-demo

基于tus协议实现断点续传演示

基于tus协议tusdotnet方案基本demo

关于此协议实现原理这里不做阐述,请参照上述github地址自行了解,本文只是给出.NET Core方案下的基本demo,我们上传一个大文件然后通过进度显示上传进度以及对上传可暂停可继续,专业点讲就是断点续传,首先肯定是引入tus脚本和需要用到的bootstrap样式,我们将进度条默认隐藏,当上传时才显示,所以我们给出如下HTML。

<div class="form-horizontal" style="margin-top:80px;">
  <div class="form-group" id="progress-group" style="display:none;">
    <div id="size"></div>
    <div class="progress">
      <div id="progress" class="progress-bar progress-bar-success progress-bar-animated progress-bar-striped" role="progressbar"
         aria-valuemin="0" aria-valuemax="100">
        <span id="percentage"></span>
      </div>
    </div>
  </div>
  <div class="form-group">
    <div class="col-md-10">
      <input name="file" id="file" type="file" />
    </div>
  </div>
  <div class="form-group">
    <div class="col-md-offset-2 col-md-10">
      <input type="submit" id="submit" value="上传" class="btn btn-success" />
      <input type="button" id="pause" value="暂停" class="btn btn-danger" />
      <input type="button" id="continue" value="继续" class="btn btn-info" />
    </div>
  </div>
</div>

接下来就是使用引入的tus脚本,也没什么太多要讲解的,直接上代码,这里稍微注意的是在如下元数据(metadata)属性对象定义给出实际文件名,便于在后台最终将上传的文件本文来源gaodai$ma#com搞$代*码网2转换为目标文件,至少得知道文件扩展名,对吧。

<script type="text/javascript">
  $(function () {
    var upload;

    //上传
    $('#submit').click(function () {

      $('#progress-group').show();

      var file = $('#file')[0].files[0];

      // 创建tus上传对象
      upload = new tus.Upload(file, {
        // 文件服务器上传终结点地址设置
        endpoint: "files/",
        // 重试延迟设置
        retryDelays: [0, 3000, 5000, 10000, 20000],
        // 附件服务器所需的元数据
        metadata: {
          name: file.name,
          contentType: file.type || 'application/octet-stream',
          emptyMetaKey: ''
        },
        // 回调无法通过重试解决的错误
        one rror: function (error) {
          console.log("Failed because: " + error)
        },
        // 上传进度回调
        onProgress: onProgress,
        // 上传完成后回调
        onSuccess: function () {
          console.log("Download %s from %s", upload.file.name, upload.url)
        }
      })

      upload.start()
    });

    //暂停
    $('#pause').click(function () {
      upload.abort()
    });

    //继续
    $('#continue').click(function () {
      upload.start()
    });

    //上传进度展示
    function onProgress(bytesUploaded, bytesTotal) {
      var percentage = (bytesUploaded / bytesTotal * 100).toFixed(2);
      $('#progress').attr('aria-valuenow', percentage);
      $('#progress').css('width', percentage + '%');

      $('#percentage').html(percentage + '%');

      var uploadBytes = byteToSize(bytesUploaded);
      var totalBytes = byteToSize(bytesTotal);

      $('#size').html(uploadBytes + '/' + totalBytes);
    }

    //将字节转换为Byte、KB、MB等
    function byteToSize(bytes, separator = '', postFix = '') {
      if (bytes) {
        const sizes = ['Bytes', 'KB', 'MB', 'GB', 'TB'];
        const i = Math.min(parseInt(Math.floor(Math.log(bytes) / Math.log(1024)).toString(), 10), sizes.length - 1);
        return `${(bytes / (1024 ** i)).toFixed(i ? 1 : 0)}${separator}${sizes[i]}${postFix}`;
      }
      return 'n/a';
    }
  });

</script>

搞代码网(gaodaima.com)提供的所有资源部分来自互联网,如果有侵犯您的版权或其他权益,请说明详细缘由并提供版权或权益证明然后发送到邮箱[email protected],我们会在看到邮件的第一时间内为您处理,或直接联系QQ:872152909。本网站采用BY-NC-SA协议进行授权
转载请注明原文链接:.NET或.NET Core Web APi基于tus协议实现断点续传的示例
喜欢 (0)
[搞代码]
分享 (0)
发表我的评论
取消评论

表情 贴图 加粗 删除线 居中 斜体 签到

Hi,您需要填写昵称和邮箱!

  • 昵称 (必填)
  • 邮箱 (必填)
  • 网址