net上传下载断点续传总结

一.分片上传:

  1.借助blob对象:

<script type="text/javascript">
        var bytesPerPiece = 1024 * 1024; // 每个文件切片大小定为1MB .
        var totalPieces;
        //发送请求
        function upload() {
            var blob = document.getElementById("file").files[0];
            var start = 0;
            var end;
            var index = 0;
            var filesize = blob.size;
            var filename = blob.name;

            //计算文件切片总数
            totalPieces = Math.ceil(filesize / bytesPerPiece);
            while(start < filesize) {
                end = start + bytesPerPiece;
                if(end > filesize) {
                    end = filesize;
                }

                var chunk = blob.slice(start,end);//切割文件    
                var sliceIndex= blob.name + index;
                var formData = new FormData();
                formData.append("file", chunk, filename);
                $.ajax({
                    url: 'http://localhost:9999/test.php',
                    type: 'POST',
                    cache: false,
                    data: formData,
                    processData: false,
                    contentType: false,
                }).done(function(res){ 

                }).fail(function(res) {

                });
                start = end;
                index++;
            }
        }
    </script>

2.借助开源插件:如 Web Uploader
二.文件断点续传之上传:
  1.前端使用分片上传,并使用标识识别token
  2.后端使用流式储存,并保存token
    识别token,读取请求头的range,并且append到文件流中
三.文件断点续传之下载(Web版):
  1.各浏览器本身支持分片读取,后端读取range,并定位到文件流的该位置,返回即可
四.下载,上传速度限制,主要是在两片文件流之间设置sleep时间,缓解带宽.无其他更好方法

public void DownloadFile(string fullFilePath)
{
try
{
var filename = Path.GetFileName(fullFilePath);
if (!File.Exists(fullFilePath))
{
Response.Write("<script language='javascript'>");
Response.Write("window.alert('file does not exist');");
Response.Write("</script>");
Response.End();
}
byte[] bytes = null;
using (FileStream fileStream = File.Open(fullFilePath, FileMode.Open, FileAccess.Read))
{
bytes = new byte[fileStream.Length];
fileStream.Read(bytes, 0, bytes.Length);
}
Response.Clear();
Response.Buffer = true;
Response.Charset = "UTF-8";
Response.AddHeader("Content-Disposition", string.Format(@"attachment;filename=""{0}""", HttpUtility.UrlEncode(filename)));
Response.ContentEncoding = System.Text.Encoding.UTF8;
Response.ContentType = "application/vnd.openxmlformats-officedocument.wordprocessingml.document";
Response.AddHeader("Content-Length", bytes.Length.ToString());
Response.OutputStream.Write(bytes, 0, bytes.Length);
Response.Flush();
}
catch (Exception ex)
{
throw ex;
}
finally
{
Response.End();
}
}











猜你喜欢

转载自www.cnblogs.com/hx215267863/p/11922817.html