zhangbobo

前言

不少项目中会遇到上传下载视频、更新包、应用程序等文件,此类文件的共同点就是十分巨大,我在项目中遇到过 4G 左右的文件同时 100 多台机器下载,此时如果用 post 上传和下载想一下都不可能,但百度查的话都是说调整 php.ini 的 post 的限制,但这是一个可笑的解决方法,由此就需要用另一种解决方法 -- 分片上传和下载限速

在此带大家用 php 实现一下,各种语言和框架同时适用,本次用到的是 php 的 laravel, 语言和实现的思路是一样的

如果项目中用到的分片上传,个人建议找相对应的包如 (AetherUpload-Laravel)、有条件直接用 7 牛云、阿里云等大公司的分片上传服务

分片上传

原理

  1. 将需要上传的文件按照一定的分割规则,分割成相同大小的数据块;
  2. 初始化一个分片上传任务,返回本次分片上传唯一标识;
  3. 按照一定的策略(串行或并行)发送各个分片数据块;
  4. 发送完成后,服务端根据判断数据上传是否完整,如果完整,则进行数据块合成得到原始文件。

实现

h5

h5 实现部分,h5 部分实现了把文件的分割,在上传中,告诉服务端文件的总片数和当前是第几片,各个临时文件通过 http 请求发送出去

<!doctype html>
<html>
<head>
    <meta charset="UTF-8">
    <meta name="viewport"
          content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>
    <style>
        #progress{
            width: 300px;
            height: 20px;
            background-color:#f7f7f7;
            box-shadow:inset 0 1px 2px rgba(0,0,0,0.1);
            border-radius:4px;
            background-image:linear-gradient(to bottom,#f5f5f5,#f9f9f9);
        }

        #finish{
            background-color: #149bdf;
            background-image:linear-gradient(45deg,rgba(255,255,255,0.15) 25%,transparent 25%,transparent 50%,rgba(255,255,255,0.15) 50%,rgba(255,255,255,0.15) 75%,transparent 75%,transparent);
            background-size:40px 40px;
            display: inline-block;
            height: 20px;
        }
        form{
            margin-top: 50px;
        }
    </style>
</head>
<body>
<p id="progress">
    <span id="finish" style="width: 0%;" progress="0"></span>
</p>
<form action="">
    <input type="file" name="file" id="file">
    <input type="button" value="停止" id="stop">
</form>
<script>
    var fileForm = document.getElementById("file");
    var stopBtn = document.getElementById(\'stop\');
    var upload = new Upload();

    fileForm.onchange = function(){
        upload.addFileAndSend(this);
    }

    stopBtn.onclick = function(){
        this.value = "停止中";
        upload.stop(

分类:

技术点:

相关文章:

  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2021-06-19
  • 2022-02-01
  • 2022-12-23
猜你喜欢
  • 2022-01-02
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2021-12-26
  • 2022-12-23
相关资源
相似解决方案