Ruby、Rails知识程序员Web前端之路

大文件断点续传

2017-01-01  本文已影响423人  shiy4n

对于大文件,往往需要通过断点续传来应对不稳定的网络环境。这几天正好做毕设,记下来断点续传的一些想法

H5断点续传

过程

这里其实还应该在cookie中记录下来每一个slice上传的状态,以防止用户刷新页面或关闭页面造成状态丢失,下面那段实验性代码并没有体现。

home.js

$().ready(function () {

    var $progress = $('#upload_progress');
    var $fileObj; //文件
    var $isPaused = false; //暂停记号
    var $currentIndex = 0; // 当前的slice序号
    var $errThreshold = 3; //允许的错误阈值
    var $token; //文件记号
    var $fileName;
    $('#upload_file').on("change",function () {
        $progress.progress('reset');
        $currentIndex = 0;
        $fileObj = this.files[0];
        $fileName = $('#upload_file').val().split('fakepath\\')[1];
        if ( this.files[0].size/1024/1024 > 1) {
            //分片上传
            $token = new Date().getTime();
            uploadByChunk($token,$fileName)
        } else {
            uploadSimple(this.files[0])
        }
    });

    $("#pause").on("click", function () {
         $isPaused = true;
        $("#start").enable()
    });

    $("#start").on("click", function () {
        if ($isPaused) {
            $isPaused = false;
            uploadByChunk($token,$fileName);
        }
    });

    function uploadSimple(obj) {
        var formData = new FormData();
        formData.append('file', obj);
        formData.append('time',new Date().getTime());

        $.ajax({
            url: 'home/upload',
            type: 'post',
            cache: false,
            processData: false,
            contentType: false,
            data: formData,
            success: function (res) {
                alert(res + ' from success')
            },
            error: function (err) {
                alert(err + 'from error')
            }
        })
    }

    function uploadByChunk(token,fileName) {
        var size = $fileObj.size;
        var chunkSize = 1024 * 1024;
        var chunkNum = Math.ceil(size/chunkSize);

        $progress.progress('set total', chunkNum);

        $.post( 'home/check_permission', {token: token, filename: fileName})
            .done(function (res) {
                if (res.status == 200) {
                    upload($currentIndex, token, size, fileName,chunkNum, chunkSize,0);
                    console.log('success');
                    console.log(token, size,fileName,chunkNum, chunkSize)
                } else {
                    alert(res.msg);
                }
            })
            .fail(function(err){
                alert(err.msg + ' $$$');
            })
    }
    /*index of chunk
    * token
    * total size
    * filename
    * total chunk
    * size of per chunk
    * error time*/
    function upload(i, token, size, fileName, chunkNum, chunkSize, errTime) {

        $currentIndex = i;

        if ($isPaused) {
            return
        }
        var formData = new FormData();
        if (i < chunkNum && errTime<$errThreshold) {
            var slice = $fileObj.slice(chunkSize*i, chunkSize*(i+1) > size ? size : chunkSize*(i+1));
            formData.append('slice', slice, i);
            formData.append('token', token);
            formData.append('size', size);
            formData.append('filename', fileName);
            formData.append('chunk',i);
            console.log(formData.data);
            $.ajax({
                url: "home/upload_by_chunk",
                type: 'POST',
                cache: false,
                processData: false,
                contentType: false,
                data: formData,
                success: function (res) {
                    if (res.status == 200) {
                        upload(i+1, token, size, fileName, chunkNum, chunkSize,errTime);
                        $progress.progress('increment');
                        console.log(i + ' has been uploaded');
                    } else {
                        upload(i, token, size, fileName, chunkNum, chunkSize, errTime+1);
                        console.log(res.msg);
                    }
                },
                error: function (err) {
                    console.log(err.msg);
                    upload(i, token, size, fileName, chunkNum, chunkSize,errTime+1);
                }
            })
        } else if (errTime >= $errThreshold) {
            $progress.progress('set error');
            alert('failed');
        } else if (i >= chunkNum) {
            $.post("home/uploaded", {token: token, size: size, filename: fileName})
                .done(function (res) {
                    if (res.status == 200) {
                        alert('success')
                    } else {
                        $progress.progress('set error');
                        alert(res.msg)
                    }
                })
                .fail(function () {
                    upload(i, token, size, fileName, chunkNum, chunkSize, errTime+1);
                })
        }
    }
});

index.html.erb

<h1>Home#index</h1>
<p>Find me in app/views/home/index.html.erb</p>

<div>
  <a href="javascript:;" class="a-upload">
    <input type="file" name="file" id="upload_file">
    <i class="file icon"></i>upload
  </a>
  <div class="ui indicating progress" data-value="0" data-total="10" id="upload_progress">
    <div class="bar">
      <div class="progress"></div>
    </div>
    <div class="label"></div>
  </div>
  <button class="ui labeled icon button" id="pause">
    <i class="pause icon"></i>
    Pause
  </button>
  <button class="ui button" id="start">
    <i class="play icon"></i>
    Start
  </button>
</div>

<%= link_to_if(current_user.nil?, 'login', {controller: 'devise/sessions', action:'new'}) do
    link_to('logout',:destroy_user_session, method: :delete)
  end
%>

-服务器
也是按照之前的思路编写
服务端也是需要记录下每个slice的状态,防止在合并文件导致添加顺序出错。

最开始,我是先保存每个slice然后最后在验证文件的时候在合并。但是合并slice的时间较长,也就是上传会卡在百分之99那里,感觉这样体验会很糟糕,因此我想着使用多线程合并,当时我的思路参考的是多线程树形求和做法,然而我并没有这么做。。。。。。我想着既然最后一步很慢,何不把这段时间分散到每一片上传中,这样其实用户并不会感受到最后一步很慢。所以就有了以依次追加写入文件,但是这样做一定要保证slice的顺序,所以一定验证slice的状态。另外,由于MD5验证问题还没想好,我暂时用对比文件大小来确认文件,但这是不可取的,用文件大小对比是很不牢靠的。

下面贴出来实验性代码。。。

#home_controller.rb
class HomeController < ApplicationController
  before_action :authenticate_user!
  def index

  end

  def check_permission

    token = params[:token]
    file_name = params[:filename]

    if session[:last_token].nil? || session[:last_token] != token.to_s
      session[:last_token] = token.to_s
      session[:slice_status] = []
    end

    if !token.nil? && !file_name.nil?
      dir = "#{Rails.root}/public/uploads/#{token.to_s}/"
      Dir.mkdir(dir) unless Dir.exist?(dir)
      render json: {status: 200, msg: 'success'}
    else
      render json: {status: 500, msg: 'params error'}
    end

  end

  def upload
    temp = params[:file]
    @user_file= UserFile.new
    @user_file.info= temp
    @user_file.is_shared= false
    @user_file.is_folder= false
    @user_file.belong_to_user= current_user
    if @user_file.save
      render json: {status: params[:time]}
    else
      render json: {status: false}
    end
  end

  def upload_by_chunk
    token = params[:token]
    chunk = params[:chunk] # index of the slice
    slice = params[:slice]
    size = params[:size]
    file_name = params[:filename]
    #chunk_number = params[:chunks]
    if !chunk.nil? && !token.nil? && !slice.nil? && !size.nil? && !file_name.nil?
      dir = "#{Rails.root}/public/uploads/#{token.to_s}/"
      if Dir.exist?(dir) && !session[:slice_status].nil? && !session[:slice_status][chunk.to_i]
        File.open(dir+file_name.to_s, "ab") do |f|
          f.write(slice.read)# append mode 写入文件
        end
        session[:slice_status][chunk.to_i] = true
        render json: {status: 200, msg: 'success'}
      elsif session[:slice_status][chunk.to_i]
        render json: {status: 200, msg: 'uploaded before'}
      else
        render json: {status: 500, msg: 'folder not founded'}
      end
    else
      render json: {status: 500, msg: 'params incorrect'}
    end
  end

  def uploaded
    token = params[:token]
    size = params[:size]
    file_name = params[:filename]

    if token.nil? || size.nil? || file_name.nil?
      render json: {status: 500, msg: 'params error'}
    else
      file_path = "#{Rails.root}/public/uploads/#{token.to_s}/#{file_name.to_s}"
      if File.exist? file_path
        if File.size(file_path) == size.to_i
          render json: {status: 200, msg: 'success'}
        else
          render json: {status: 500, msg: 'the size of the file is incorrect'}
        end
      else
        render json: {status: 500, msg: 'file not founded'}
      end
    end

  end
end


untitled
上一篇下一篇

猜你喜欢

热点阅读