[Open source app] upload large files with Html5+resumablejs drag and drop

Source: Internet
Author: User
Tags throw exception

Objective:

Large file transfer has always been a major technical difficulty. When the file is too large, some sex commits all the content into the memory is unrealistic. Large files also have problems with whether to support breakpoint transfer and multiple file simultaneous transfers.

Taking Resumablejs as an example, this paper introduces how to implement large file transfer in ASP. At the same time, this paper uses the new features of HTML5: Support drag and drop.

The main technical point of this paper is: How to receive Resumablejs content (the official website is not very clear) and how to merge files, difficult.

Note: The original blog, this article for the original site personal code backup used, not many comments, if you do not understand, please give in the comments.

effect :

ASPX File:

Filehandler

Using system;using system.collections.generic;using system.io;using system.linq;using System.Web;namespace uploadtest{//<summary>//Summary description for Filehandler//</summary> public class File        Handler:ihttphandler {string _tempfolder;        Object _lock = new Object (); public void ProcessRequest (HttpContext context) {_tempfolder = context.            Server.MapPath ("~/temp"); var method = context.            Request.httpmethod; if (method.            Equals ("GET")) {Handleget (context); } if (method.            Equals ("POST")) {Handlepost (context); }} private void Handlepost (HttpContext context) {var queryString = context.            Request.Form;            if (Querystring.count = = 0) return;           try {//Read parameters var Uploadtoken = querystring.get ("Upload_token");     int resumablechunknumber = Int.                Parse (Querystring.get ("Resumablechunknumber")); var resumabletotalchunks = Int.                 Parse (Querystring.get ("resumabletotalchunks")); var resumabletotalsize = long.                                Parse (Querystring.get ("resumabletotalsize"));                var resumablefilename = querystring.get ("Resumablefilename"); Save File if (context. Request.Files.Count = = 0) {context.                 Response.statuscode = (int) System.Net.HttpStatusCode.InternalServerError; } else {var FilePath = string.                    Format ("{0}/{1}/{1}.part{2}", _tempfolder, Resumablefilename, resumablechunknumber.tostring ("0000"));                    var directory = Path.getdirectoryname (FilePath);                    if (file.exists (directory)) {file.delete (directory); } if (! Directory.exIsts (directory)) {directory.createdirectory (directory); } if (! System.IO.File.Exists (FilePath)) {context. Request.files[0].                    SaveAs (FilePath);                        } if (IsCompleted (directory,resumabletotalchunks,resumabletotalsize)) {                    Mergefiles (directory);            }}} catch (Exception Exception) {throw Exception; }} private void Handleget (HttpContext context) {var queryString = context.            Request.QueryString;            if (Querystring.count = = 0) return;                try {//Read parameters var Uploadtoken = querystring.get ("Upload_token"); int resumablechunknumber = Int.                Parse (Querystring.get ("Resumablechunknumber")); VaR resumablefilename = Querystring.get ("Resumablefilename"); var resumablechunksize = long.                 Parse (Querystring.get ("resumablechunksize")); var FilePath = string.                 Format ("{0}/{1}/{1}.part{2}", _tempfolder, Resumablefilename, resumablechunknumber.tostring ("0000")); Check for existance and chunksize if (System.IO.File.Exists (FilePath) && new Fi Leinfo (FilePath). Length = = resumablechunksize) {context.                    Response.Status = "OK"; Context.                 Response.statuscode = 200; } else {context.                    Response.Status = "404 Not Found"; Context.                Response.statuscode = 404;            }} catch (Exception Exception) {throw Exception; }} private bool IsCompleted (string Directory,int numchunks, LOng totalsize) {var physicalfolder = Path.Combine (_tempfolder, directory);            var files = directory.getfiles (Physicalfolder); Numbers if (Files.            Length! = numchunks) return false;            Files All exisit var fileName = path.getfilename (directory); for (int i = 1; I <= numchunks; i++) {var FilePath = string.                Format ("{0}/{1}.part{2}", Directory, FileName, i.tostring ("0000")); if (!                File.exists (FilePath)) {return false;            }}//size Long tmpsize = 0; foreach (var file in files) {tmpsize + = new FileInfo (file).            Length;        } return totalsize==tmpsize;                    } private void Mergefiles (string directorypath) {Lock (_lock) { if (Directory.Exists (DIRECTORYPAth) {var fileName = Path.getfilename (DirectoryPath);                        var folder = Path.getdirectoryname (DirectoryPath);                        var TempPath = Path.Combine (DirectoryPath + ". tmp");                        var files = directory.getfiles (DirectoryPath); Files = files. (f = f).                        ToArray ();                        FileStream Wholestream = new FileStream (TempPath, Filemode.append, FileAccess.Write); for (int i=0;i<files. length;i++) {FileStream parcialstream = new FileStream (Files[i], Fi                            Lemode.open);                            BinaryReader parcialreader = new BinaryReader (parcialstream);                            byte[] buffer = new Byte[parcialstream.length];                            Buffer = parcialreader.readbytes ((int) parcialstream.length); BinaryWriter parcialwriter = new BinaryWriter(Wholestream);                            Parcialwriter.write (buffer);                        Parcialstream.close ();                        } wholestream.close ();                        Directory.delete (directorypath,true);                                         File.move (TempPath, DirectoryPath);            }}} public bool IsReusable {get            {return false; }        }     }}

Appendix:

1 Technical Difficulties

A. The file is too large. modifying Webconfig is useless.

B. The breakpoint continues to pass.

C. multiple file uploads.

2 Resumable.js

api:http://www.resumablejs.com/

Work Flow:

Drag file to Div---start uploading, uploadstart, progress events, compete

Main parameters:

Get:

resumablechunknumber=1&
resumablechunksize=1048576&
resumablecurrentchunksize=1048576&
resumabletotalsize=27778318&
resumabletype=&
resumableidentifier=27778318-samples7z&
resumablefilename=samples.7z&
resumablerelativepath=samples.7z&
Resumabletotalchunks=26

Post:

————————— –111061030216033
Content-disposition:form-data; Name= "Resumablechunknumber"

140
————————— –111061030216033
Content-disposition:form-data; Name= "Resumablechunksize"

1048576
————————— –111061030216033
Content-disposition:form-data; Name= "Resumablecurrentchunksize"

1048576
————————— –111061030216033
Content-disposition:form-data; Name= "Resumabletotalsize"

171309601
————————— –111061030216033
Content-disposition:form-data; Name= "Resumabletype"

————————— –111061030216033
Content-disposition:form-data; Name= "Resumableidentifier"

171309601-sample7z
————————— –111061030216033
Content-disposition:form-data; Name= "Resumablefilename"

sample.7z
————————— –111061030216033
Content-disposition:form-data; Name= "Resumablerelativepath"

sample.7z
————————— –111061030216033
Content-disposition:form-data; Name= "Resumabletotalchunks"

163
————————— –111061030216033
Content-disposition:form-data; Name= "File"; Filename= "Blob"
Content-type:application/octet-stream

Xxxcontent
————————— –309022088923579–

[Open source app] upload large files with Html5+resumablejs drag and drop

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.