Framework Basics: Ajax Design (III)---integrated AJAX upload Technology

Source: Internet
Author: User
Tags nginx server

Before that let me sigh about the current development of the front-end atmosphere. I met a lot of people, give me the idea is that this thing this framework has, the thing that the framework did, the front end, learn a few frameworks, this piece of patchwork that piece of it just fine. In fact, I want to ask, everything is the framework to do, then you what? Will it blow? Will tear the force?

I wrote on my resume focus on the original JS, has been a few people laughed. I have never understood that the framework will be obsolete and the foundation will never be obsolete. Away from the frame, I can live, I will write my own framework, I also in the front-end modular way of my own groping, I also in the front-end how more simple, more rapid development of the road groping. Is there a frame to do, I will zuochishankong wait to die?

The front end is too impetuous, I also do not care to be other people's eyes of the wonderful. I go to the front end, I go to do the separation, I go to write back end, every day always spend some time on my favorite things. I know I am very stupid, some play not play, but also to see the code. That I have no way, I do wonderful work for a long time, because I have their own dreams, I have their own pursuit.

Please do not say in front of me, you this thing people have done. What's the matter with you? When they do, there are thousands of dead people in front of you. Is it because they did it that I quit? Please don't be shortsighted. I do not hide why I do the front-end, now enumerate my reasons for the front end, you and I do?

      1. Docking UI, need to dabble in page design, layout and landscaping. Learn to aesthetic, learn to stand on the user's perspective to see their own things. Of course I do not deny that the UI is also more sister
      2. Docking JS, the front-end core technology test. Think of how to write efficient maintainable code for page function implementation, old and new technology compatibility and abandonment
      3. Docking architecture, front-end performance optimization, program robustness and fault tolerance, the integration of various framework resources, from DNS resolution to page rendering to the cross-domain learning of various processes in front of you
      4. Docking backend, new and old technology changes, is never the front end, the back end of the same need to go with the change. So understand back end, design back end, write back end, always need you to understand
      5. Docking server, reverse proxy, load balancing, request distribution fault-tolerant integration and so on, don't you need to understand? Is it enough to just hit a JS?
      6. The front end of the future, any project use and display, are inseparable from the front end. Because the front-end first contact is the user, is the development of the most core resources. The front end is the frontline of the entire front.
      7. The most important. The front end is just starting, not very mature, can contact all the acoustic and the bottom, optimization, development, debugging, and even change the world, is possible. The back end is too mature, contact too much is the frame, highlight siege, need deeper accumulation and treason.
      8. Most importantly, the front-end is relatively good in the pre-pay period. After all, life, poetry and distance are less important than bread, alive, everything is possible.

Previously released Ajax Universal Solutions, Core Ajax publishing requests, and integrated polling. This trip to a foreign site, and then found the Ajax Level2 upload files, so there is the Ajax upload file integration into the idea of Ajax solutions Level2 improvements are not introduced, not clear can go to the previous few blog to see. We cut into the subject directly.

Concept Introduction:

1. js Formdata:js in the new version of the Formdata object has been supported, you can initialize an empty form, or initialize the existing form, the browser test code.

  

2. Browser support: The browser has supported input=file when viewing the file, including the size of the file and type, the browser test is as follows

3. XMLHttpRequest: Support for sending (send method) new data types, including,,,, DOMString Document FormData Blob File ,,ArrayBuffer。具体参见ajax设计方案的规范

Tool Preparation:

1. Front-end Code

2. Nginx Server (Detach)

3. IIS server (deployment background)

4. Background code (WebAPI)

What not much to say, first put code:

Front-End Code:

        /* * Ajax upload file * URL file upload address * fileselector input=file Selector       (Support multi-file upload, as long as the background interface support) * Size File Limit sizes * FileType file limit type MIME type *        Success Upload successful processing * ERROR upload failed processing * Timeout Timeout processing * * return:status:0 Please select File * 1 exceeds file limit size * 2 not allowed File format * */upload:function (url,fileselector,size,filetype,success,error,timeout) {var formdata = n            EW FormData (), Filenode = Document.queryselector (fileselector), FileCount = Filenode.files.length,data={},result ={}; The following is an upload file restriction check if (FileCount > 0) {tool.each (Array.prototype.slice.call (filenode.files ), function (value) {//Check file size if (value.size > size) {result          ["status"] = 1;              result["errmsg"] = "File limit size exceeded"; }else{//Check the file format. Because Formdata is supported, the IndexOf (H5) If of the array is supported (Filetype.indexof (value.t                            ype) = = =-1) {result["status"] = 2;                        result["errmsg"] = "non-allowable file format";                        }else{formdata.append (Value.name,value);                    };                };            });                }else{result["status"] = 0;            result["errmsg"] = "Please select File";            };   if (result.status!== undefined) return result; If an error message is thrown directly, end running Var ajaxparam ={type: "Post", Url:url, Data:fo Rmdata, Isformdata:true, success:success, Error:error, timeout            : timeout};        Ajax.common (Ajaxparam); },    };

Backend Interface Code (C # WEBAPI), the code is relatively simple, can complete the test.

[Route ("upload3")]         Public AsyncTaskPostFormData () {//Check If the request contains Multipart/form-data. //Check if the request contains Multipart/form-data            if(!Request.Content.IsMimeMultipartContent ()) {                Throw Newhttpresponseexception (Httpstatuscode.unsupportedmediatype); }            stringRoot = HttpContext.Current.Server.MapPath ("~/uploadfile"); varProvider =NewRenamemultipartformdatastreamprovider (root); Try            {                //Read the form data. //reading form data                varTask =awaitRequest.Content.ReadAsMultipartAsync (provider). ContinueWith (t =                {                    if(t.isfaulted | |t.iscanceled)                    {Request.createerrorresponse (httpstatuscode.internalservererror, t.exception); }                    stringFileName =string.                    Empty; foreach(Multipartfiledata fileinchprovider. FileData) {FileName=file.                    LocalFilename; }                    //returns the file full path after uploading                    return NewHttpresponsemessage () {Content =Newstringcontent (FileName)};                }); returnRequest.createresponse (Httpstatuscode.ok); }            Catch(System.Exception e) {returnRequest.createerrorresponse (Httpstatuscode.internalservererror, E); }        }        ///        ///Rename an uploaded file///         Public classRenamemultipartformdatastreamprovider:multipartformdatastreamprovider { PublicRenamemultipartformdatastreamprovider (stringroot):Base(root) {} Public Override stringgetlocalfilename (System.Net.Http.Headers.HttpContentHeaders Headers) {//intercepting file extensions                stringExp = path.getextension (headers. ContentDisposition.FileName.TrimStart ('"'). TrimEnd ('"')); stringName =Base.                Getlocalfilename (headers); returnName +exp; }        }

Browser test results (supported by almost all major browsers except IE10)

The test code is as follows:

            var temp = ajax.upload ("/api/ajaxupload/upload3/", "#file1", 1024x768 * 1024x768 * 1, ["Image/png", "image/bmp"], function (data) {                if (data = = "true") {                    alert ("Upload succeeded!") ");                }                if (data = = "Error") {                    alert (data);                }            });            Console.log (temp);

The format limit test results are as follows

1. Select a file that exceeds the size of the limit

2. Select a file that is not allowed to format

3. Upload File not selected

Successful File Upload test

IE10, 11

Safari

Firefox

Google

Opera

Edge

360 browser

Here's a little bit of the problem.

  Issue one ie8-9 compatibility issues

In Compatibility site (http://caniuse.com/) query compatibility, Ajax LEVE2 supports ie10+ version, so if you upload files using pure front-end code on ie8-9, only the traditional form tags

The HTML code is as follows:

<form id= "Formupload" action= "/api/ajaxupload/upload2/" method= "post" enctype= "Multipart/form-data" target= " Framfile ">    <input name=" isIE8 "type=" text "value=" 1 "readonly style=" Display:none "/> <input id=    " Iefile "type=" file "name=" age "/>    <input type=" Submit "value=" submit "></form><iframe id=" Framfile "Name=" Framfile "src=" postmsg.html "></iframe>

Disadvantages:

1. Each time the form submission will refresh the page, if you want to do asynchronous no refresh, use the IFRAME to submit the page

2. ie8-9 cannot check the file size and type on the front end (the file component using IE is unsafe because it can modify all files on the system, is vulnerable to attack, and the browser is closed by default)

3. The upload file interface cannot have a return value, otherwise the interface return value will be downloaded as a file under IE8, and the return value cannot be obtained (using n methods), but in other browsers, Ajax success events will be judged, the test image is as follows

Some suggestions : If you really want to do ie8-9, now the common solution is to add Flash plug-ins and Ajax Level2 uploads, support H5 with Ajax uploads, does not support the initialization of Flash upload plugin.

PS: For those paranoid, must be in ie8-9 with pure front-end code support upload, there is a compromise scheme, and this idea similar, but I did the optimization, the idea is as follows:

Requires 2 interfaces: Upload a file interface, ie8-9 upload Results query interface

A. No-refresh upload using form first (Ifarme)

B. The background receives the FORMDATA data to determine whether the upload is ie8-9, if the user uploads the file is a successful state change (regardless of the repository or other places), or directly return the upload results

C. The front end in the form of the submission, the initiation of a poll results, if the results, the direct end of polling, the results of the query interface will also be the user's upload file status empty

  Problem two general AJAX requests and FORMDATA requests, background fetch problems.

Traditional HTTP requests, you can get data directly in the interface parameters, but using Formdata for AJAX requests, the background interface needs to fetch data from the Formdata object, including the file. Because this I write the background interface when the confused forced a long time, and then left to check the right to check, and finally understand the value of the way is not the same.

  Question three about Formdata upload file, specific can upload how much file limit problem

The limitation of uploading files depends on the size of the Web container to accept the uploaded files, and the web containers such as Tomcat and IIS have their own setting methods, specifically search engines, you know.

  Problem four front-end to large file transfer solution, specifically refer to this article

In the new version, which is the version that supports H5, a file object can be used to cut files, because the files taken in Input=file are file types, the file object has a method slice, you can cut files, and then assign a XHR upload. Mainly in the background of the cutting file reorganization problem is not very clear, so I do not have the integration of large file upload method.

Code is integrated github:https://github.com/GerryIsWarrior/ajax dot star is my biggest encouragement, what questions can blog, email, Leave a message on GitHub

This time uploading the version, the code has changed, the following changes:

    1. Increased Formdata data transfer method (PostFormData), automatically using default raw data transfer if the browser does not support Formdata
    2. New types of judging methods, judging types
    3. Update each method to determine if the incoming parameter obj is an array and the browser supports the new feature of H5 directly with the Foreach method

My full stack bookmark, this update has organized the domestic top Internet and some famous Internet companies recruitment site, I hope you find a good job, ^_^

GitHub Address: Https://github.com/GerryIsWarrior/MyBookmarks

Framework Basics: Ajax Design (III)---Integrated AJAX upload technology

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.