Mobile uploads images (files) via Ajax and displays them in the foreground-via H5 's Formdata object

Source: Internet
Author: User

Some time ago encountered the mobile side need to upload pictures and video problems, has been through Ajax asynchronous submission of data, so in search of the way to upload files through Ajax. Found a new Formdata object in H5, this object can be directly bound to the HTML form element, and then submitted through the AJAX submission of this object directly.

To invoke video and audio on the mobile side:

<inputtype= "File"Accept= "image/*"Capture= "Camera">//Call album and webcam<inputtype= "File"Accept= "video/*"Capture= "Camcorder">//Video<inputtype= "File"Accept= "audio/*"Capture= "Microphone">//Audio

Take an example of uploading a picture

The code in HTML:

<type= " file" id= "File " name= " file" Accept/>

Of course, if you want to upload more than one image is also possible, just add "multiple" property

<type= " file" id= "File " name= " file" Accept= "image/*"/>

(You just have to write the type and ID on it.)

We can see the contents of the upload through the print table.

var file = document.getElementById ("file"); Console.log (file.files);

What we get is a generic collection similar to an array, and we can take the same as an array to the first I: File.files[i]

In JS, we need to start with a new Formdata object.

var form = new FormData ();

Then add the images we've passed to this Formdata object, and use the Append

Form.append ("Fileimg", file.files);

And then we could pass the data through Ajax, and I used the jquery Ajax

$.ajax ({      "post",      "transmitted Address",      data:form,      false//  Note that this should be set tofalse      ,    //false      ,    / / cache      function(data) {          console.log (data);}            })

Note: There are three parameters that are set to false:

ContentType: Content encoding type when sending information to server, default is application/x-www-form-urlencoded

ProcessData: The data is converted to a string by default

Cache: Set to false this page will not be cached

If this is a cross-domain transmission, there will be problems, the file is not set datatype: "Jsonp", there will be problems, want to cross-domain words try not to use this method (I compare dishes will not pass, manual cover face, welcome guidance), of course, through the background settings allow access to the address can also

Formdata objects are closed, there is no way to print to the print table through Console.log (form), you want to see the values in the Form object can be viewed through the network of the browser debugging tool

Usually we pass the data, of course not just the file, so we need to append each one to the formdata.

We can add a form form to the HTML and get its ID, and then the data in the form form can be tied directly to the formdata.

Html:

<formID= "Formtest">    <inputtype= "text"name= "Name1" />    <inputtype= "text"name= "Name2"/>    <inputtype= "File"name= "File"ID= "File"/></form>

Js:

var formtest = document.getElementById ("formtest"); var New FormData (formtest);

This automatically gets the name and value in the form form and adds it to the Formdata object.

Usually after we pass in the picture, we want to show the picture in the foreground page, here we need to use the H5 filereader.

My practice is: put a picture on the front end, click on the image to trigger the hidden upload file input,input change when the call prewviewimg method

Html:

<Divclass= "Pic"ID= "Wholeimg"><imgID= "IMG1"src= "Img/a11.png"/></Div><inputtype= "File"name= "whole"ID= "whole"style= "Display:none;"Capture= "Camera"onchange= "previewimg (this)" />

Js:

$ ("#wholeImg"). Click (function(){    $("#whole"). Click ();})functionpreviewimg (file) {//determine if FileReader is supported    if(window. FileReader) {varReader =NewFileReader (); } Else{alert ("Your device does not support the Picture preview feature, please upgrade your device if you need this feature!" "); }    varPrediv = document.getElementById ("wholeimg"); //Get Pictures    if(File.files && File.files[0]){        varReader =NewFileReader (); Reader.onload=function(e) {varimg = document.getElementById ("IMG1"); Img.setattribute ("SRC", E.target.result); } reader.readasdataurl (file.files[0]); }}

So you can display the contents of the picture.

Mobile uploads images (files) via Ajax and displays them in the foreground-via H5 's Formdata object

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.