"Pure Dry Goods" 4 years ago to solve the matter, today only experimental success: Browser native tile upload file

Source: Internet
Author: User

First week of software development work (not counting one weeks for a probationary period, no salary trial). Because it is not a software professional, and has not been trained and related work experience. The boss is not at ease, but let me have a try. The first thing to do is upload files, see the progress in real time, and preview after uploading. The preview file type has Word,ppt,excel,flash, and the video gets a preview by frame. Office files are displayed after the server-side is turned into HTML.

Was satisfied, left, and then stayed in that company for two years.

things that are not resolved :

Upload large files, block uploads, browser native not supported, need to use third-party plugins. The most fundamental reason is the browser-side JS to consider the security issues, not allowed to read the file content.

Now IE10 and other mainstream browser support HTML5, JS built-in FileReader objects, WebSocket, these listen are cool.

Moments of great significance:

I realized the original zoning block upload, the road is very rugged, the result is very good.

This realization identifies the future irreplaceable status of the browser.

I only introduce the dry parts, other details, I believe that interested people already know.

First, the chunked upload, must be able to read the file content in JS, FileReader object is the key. This is an asynchronous read method that must get the contents of the file within the OnLoad event. To really block the upload, rely on onprogress to read the file progress is not enough, and the file is too large when the browser will be stuck. The slice function of file is the key, which blocks the contents of files, triggers each onload event, marks the completion of a piece of content, and can further process the file within the event, such as uploading.

FileReader has four read methods,

Astext, only recommended for reading text files

Asdataurl, the read media file can be used directly for the SRC attribute, or the contents of the HTML file can also be read as Dataurl

Asarraybuffer, Official Introduction said can not be used directly, need to rely on DataView, such as Int8array or Int32array. In fact, this is conditional, since the design is certainly useful, when the WebSocket binarytype= ' Arraybuffer ', the Event.target.result can be directly send to the server side , The server-side receive type is byte[], corresponding to the Superwebsocket newdatareceived event. The current problem, when the file size is 2k, the server can receive, and when the file is 18K, Superwebsocket reported protocolerror error. It is not yet known what the threshold is, or what parameters need to be set, and the rfc6455 protocol does not seem to limit the maximum size. Or did you see the agreement last year and check it later?

Key Settings for WebSocket:

New WebSocket ("ws://127.0.0.1:2014"= "Arraybuffer";//If you do not set this property, you cannot send the byte array directly to the server. If the Superwebsocket service is reported to ProtocolError, it may be caused by this reason.

The Websocket.send method is called in the OnLoad event:

Client.send (this. result);

The core code that combines the slice and onload event chunked uploads:

         This. Result;            Loaded + = res.bytelength;            if (Loaded < fileSize)// Continue reading next block {Readblob (loaded); times + = 1; Console.log ("Next block,times:" +Else// Read complete Console.log ("Done loaded:" + Loaded + ", size:" +       

How to use slice:

function Readblob (start) {    var blob = Currentfile.slice (start, start + step);       Reader.readasarraybuffer (BLOB);}

     //0 1 2 3//0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1//+-+-+-+-+-------+-+-------------+-------------------------------+     //| F| r| r| r| opcode| m|    Payload Len |     Extended Payload Length | //| i| s| s|  s| (4) |     a|             (7) |     (16/64) | //| n| v| v|       v| |             s|   |     (if payload len==126/127) | //| |1|2|3| |             k|                               |     | //+-+-+-+-+-------+-+-------------+ - - - - - - - - - - - - - - - +     //|     Extended payload length continued, if payload len = = 127 | //+ - - - - - - - - - - - - - - - +-------------------------------+     //| |     Masking-key, if MASK set to 1 | //+-------------------------------+-------------------------------+     //|          Masking-key (continued) |     Payload Data | //+-------------------------------- - - - - - - - - - - - - - - - +     //: Payload Data continued ...://+ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - +     //|     Payload Data Continued ... | //+---------------------------------------------------------------+

In terms of frame structure, there are 8 bytes representing the content length, so what is the content length limit set? Who is familiar with Superwebsocket


asbinarystring Now does not approve of the method used, and there is no such method in IE.

If the server side, do not support websocket and do not want to use third-party support such as superwebsocket such components, you can directly use the Ajax true chunked upload, to determine that each request will establish a new connection.

Uploading notes using Ajax dry foods:

It is recommended to turn Arraybuffer into Int32array so that the client translates faster. Server-side with int32[] receive, if the Int8array service side can also be received with Int32.

emphasis : Async:false guarantee Order, also can be uploaded each time the additional parameter number, server-side reassembly order.

Int8array, the server can directly turn each element into byte.

  [System.Web.Mvc.HttpPost]        public actionresult File (int[] datas)        {             if NULL )            {                var d = datas. ToList (). ConvertAll (x = = (byte) x). ToArray ();            }             return Content ("OK");        }

Int32array, the server can use the bitconverter.getbytes (int) method.

[System.Web.Mvc.HttpPost] PublicActionResult File (int[] datas) {            if(Datas! =NULL) {List<byte> bs =Newlist<byte>();//received file buffer object for(inti =0; I < datas. Length; i++)                {                    foreach(varIteminchbitconverter.getbytes (Datas[i])) {BS.                    ADD (item); }                }            }            returnContent ("OK"); }

Ajax Client Upload Key method:

  $.ajax ("/home/file", {                new Int8array (thisfunction  (res) {                    Console.log (res);                },                false,                type:"POST"            });

This call is in the OnLoad event in FileReader.

If you think it's meaningful, don't forget to "recommend".

"Pure Dry Goods" 4 years ago to solve the matter, today only experimental success: Browser native tile upload file

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.