Summary of several ways to upload web

Source: Internet
Author: User

Problem

File uploads are widely used in web development.

File upload refers to the process of uploading local pictures, videos, audio and other files to the server for other users to browse or download.

The following summarizes the common file (image) Upload method and key points to deal with.

form Upload

This is the traditional form form upload, using the form form of the input[type= "file" control, you can open the system's File selection dialog box, so as to achieve the purpose of selecting files and uploading, its benefits are multi-browser compatible, it is the most common Web Developer file upload method.

The code for the form is as follows:

<formMethod= "POST"Action= "Http://uploadUrl"enctype= "Multipart/form-data">    <inputname= "File"type= "File"Accept= "Image/gif,image.jpg" />    <inputname= "token"type= "hidden" />    <inputtype= "Submit"value= "Submit" /> </form>

Here are a few key points to the form upload:

method="post": Submit data by post
enctype="multipart/form- data": Upload file in multipart format, at which time the request header will display Content-type:multipart/form-data; boundary=-- WEBKITFORMBOUNDARYZR34CWJ67R95KQC9
action: Indicates the uploaded server processing address
type="file": Uploading using the file control of input
If you are uploading multiple files in bulk, you can set the Name property of input[type= "file" to such as: Name= "file[]"
acceptproperty is a new property of HTML5, which specifies that a file can be
Upload a submitted file type

The uploaded trigger event can be triggered by the input[type= "file", onChange or it can be submitted by a separate button, with onClick input[type="hidden"] Some other parameters such as token source verification and so on.

Ajax No Refresh upload

Ajax no Refresh Upload method, essentially the same as the form upload, just put the contents of the form to use AJAX submissions, and by the front-end to determine the results of the request after the return of the display, do not like the direct form upload to refresh and jump page. Here, we use jquery as the JS Base library for manipulating the DOM and creating AJAX submissions.

The HTML code snippet is as follows:

<form>    <input id= "file" name= "file" type= "file"/>    <input id= "token" name= "token" type= "hidden "/></form>

The JavaScript code snippet is as follows:

$ ("#file"). On ("Change", function () {  var formData = new FormData ();  Formdata.append ("File", $ ("#file") [0].files);  Formdata.append ("token", $ ("#token"). Val ());  $.ajax ({      URL: "Http://uploadUrl",      Type: "POST",      data:formdata,      processdata:false,      Contenttype:false,      success:function (response) {              //Specify interface actions based on return results}  });

We use file controls change to trigger upload events, and of course you can use a button to make a single submission. When submitting the data, the object is used to FormData send the binary file, the FormData constructor provides the append() method, in addition to directly add the binary file can also be accompanied by some other parameters, as XMLHttpRequest the parameters of the instance is submitted to the server.

Using the Ajax method provided by jquery to send a binary file requires two additional parameters:

processData: false//Do not serialize the data parameter, default is True
contentType: false//Do not set the Content-type request header because the file data is encoded in Multipart/form-data

Flash upload

Many times the need to upload requirements to display upload progress, interrupt upload process, large file multipart upload , and so on, then the traditional form upload difficult to achieve these functions, resulting in the use of Flash upload method, it uses flash as an intermediary agent layer, in place of the client and server communication, In addition, it also has more control over the client's file selection, much larger than the input[type= "file".

Here I used the jquery packaged uploadify plug-in to demonstrate, generally this kind of plug-in has been uploaded with the Flash file, because the data and display with the server back to the client interaction, are Flash file interface with plug-in docking.

<id= "File_upload"></div>

The HTML section is simple, when a hook is reserved, the plugin creates a Flash object inside the node, and also comes with an interface to create upload progress, cancel controls, and multi-file queue presentation.

$ (function () {  $ ("#file_upload"). Uploadify ({      auto:true,      method: "Post",      width:120,      height:30 ,      swf: './uploadify.swf ',      uploader: ' Http://uploadUrl ',      formData: {          token: $ ("#token"). Val ()      },      fileobjname: "File",      onuploadsuccess:function (file, data, response) {          //Specify interface action based on return result      }  });});

About Jquery.uploadify You can access the understanding: http://www.uploadify.com/documentation/. It is important to note that Flash is not suitable for mobile applications, and a better solution is to use FLASH+HTML5 to solve the platform compatibility problem.

Paste Upload

We found that now there are many upload applications have provided the Paste upload function, for example WebUploader , it will support QQ and then paste upload.

First, the core idea of paste upload is to listen to the paste event , then get the data in the Clipboard, and if it is a picture, trigger the upload event.

The code snippet is as follows:

$ ("textarea"). On ("Paste",function(e) {e.stoppropagation (); varSelf = This; varClipboarddata =E.originalevent.clipboarddata; if(clipboardData.items.length <= 0) {       return; }   varFile = Clipboarddata.items[0].getasfile (); if(!file) {       return; }   varFormData =NewFormData (); Formdata.append ("File", file); Formdata.append ("Token", $ ("#token"). Val ()); $.ajax ({URL:"Http://uploadUrl", type:"POST", Data:formdata,}). Done (function(response) {//specify interface actions based on return results   }); E.preventdefault ();});

As can be seen from the above code, the upload process is the same, mainly the way to get the file. When pasting (right-paste/ctrl+v) operation, trigger Clipboard event ' paste ', get content from the system Clipboard, and the system Clipboard data is saved in different locations in different browsers:

IE Kernel: windows.clipboarddata
Others: E.originalevent.clipboarddata

drag and drop upload

Drag-and-drop upload, supported by fewer browsers, because it uses the HTML5 of the two new properties (API) One is Drag and Drop , one is File API .

Upload domain monitor drag and drop three events: dragEnter , dragOver and drop , respectively, corresponding to drag-and-drop, and release three operation of the processing mechanism, of course, you can also listen to dragLeave events.

The HTML5 file API provides an FileList interface that can be used to retrieve the local file list information by dragging the e.datatransfer.files of the event to pass the file information.

The file API is only a draft in the HTML5 specification, where the file object contains only read-only properties such as file name, file type, and file size. However, some browsers provide an object named FileReader outside the draft to read the contents of the file and can monitor the read state, which provides methods such as "readasbinarystring", "Readasdataurl", "Readastext", "Abort" and so on.

The code snippet is as follows:

//DragEnter$ ("#textarea"). On ("DragEnter",function(e) {E.preventdefault ();});//DragOver$ ("#textarea"). On ("DragOver",function(e) {E.preventdefault ();});//Drop$ ("#textarea"). On ("Drop",function(e) {e.stoppropagation ();    E.preventdefault (); varFiles =E.originalevent.datatransfer.files; _.each (Files,function(file) {if(!/^image*/. Test (File.type)) {          return; }        varFileReader =NewFileReader (); Filereader.onload=function() {          //uploadfile (file);        };    Filereader.readasdataurl (file); });});

Drag and drop several key points in the upload process:

Gets a list of drag-and-drop files by E.datatransfer.files after the drop event is triggered and is e.originalevent.datatransfer.files in jquery
Drag-and-drop uploads only supports images, and File.type identifies file types in file objects.
Because it may be a multi-graph drag, so you can traverse the image upload, here is used underscore each method.
Here with Readasdataurl read the file content as a binary file, you can also convert it to Base64 mode upload, but the HTTP protocol exists in the non-binary data upload size limit to 2M.
The upload process is the same as in the previous way: Create a Formdata object and initiate an AJAX request.
Photo Upload

A photo upload can be a camera upload on a PC, or a photo upload from a mobile device such as a mobile phone. The most common form of photo uploads on a mobile phone is when we use hair photos.

Mobile phone implementation of the photo upload code:

<input type=file accept="image/*"><input type=file accept="video/*">

iOS has the ability to take photos, videos, and select local images, and some Android only select local images.

Upload and security

The file must be uploaded to the security, in addition to the front-end necessary validation, such as file type, suffix, size and other validation, it is important to do security policy in the background.

Here I cite a few points of note:

    • Background file type, size, source and other authentication required
    • Defines a. htaccess file that only allows access to files of the specified extension.
    • Generates a random file name for the uploaded file, plus the file extension that was previously generated.
    • Set the upload directory execution permission to avoid malicious people bypassing the chip extension for a hostile attack, rejecting the possibility of script execution.

Summary of several ways to upload web

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.