Using AJAX to use Formdata objects without refreshing upload file methods _jquery

Source: Internet
Author: User
Tags html form

Write in front: This article says this program has the browser compatibility problem; Newer versions of all major browsers already support this object, such as Chrome 7+, Firefox 4+, IE 10+, Opera 12+, Safari 5+, and more sensitive sites for compatibility.

In the work encountered a problem: in a page, there are 4 pieces of content, each piece contains a picture upload function, hoping to achieve a key to the four pieces of content are uploaded up.

I did not use Plug-ins to implement the upload function, is the use of input[type=file], so I encountered a problem is:

① the traditional form form will cause the page to refresh, unable to achieve these functions

② the Form serialize () serialization is submitted in an AJAX way, and cannot serialize the file stream of the uploaded file.

My existing knowledge can not be made, can only help the big God on the Internet, Baidu a bit, probably saw two programs:

① in JS to create a new form form, the page Central Plains form a copy, and then use JS to make an IFRAME, the form of target set to IFRAME, so that the content returned after submission in the IFRAME, and finally the form, IFRAME Removal

② is the following article to use the Formdata object to implement

There are other ideas of the plan of the hope that the generous enlighten!

Well, after introducing the background, let's begin by introducing our topic for today: Formdata objects.

There are two ways to create a Formdata object:

① Create an empty Formdata object, and then use the Append () method to add fields to the object

② uses an HTML form to initialize a Formdata object

Here are the following:

The first way:

var omyform = new FormData ();
Omyform.append ("username", "Groucho");
Omyform.append ("AccountNum", 123456); 
Omyform.append ("File", $ (' #file ') [0].files[0]);

$.ajax ({
 URL: '/manage/uploadimg ',
 type: ' POST ',
 cache:false,
 data:omyform,
 processdata: False,
 Contenttype:false,
 async:false
}). Done (function (res) {}). Fail (function (res) {});

The second way:

<form id= "Uploadform" enctype= "Multipart/form-data" >
 <p> Specify filename: <input type= "text" Name= " FileName "value=" "/></p>
 <p> Upload file: <input type=" file "name=" file "/></p>
  < Input type= "button" value= "Upload" onclick= "doupload ()"/>
</form>
var formData = new FormData ($ (' #uploadForm ') [0]);
Formdata.append (' num ', ' 1 ');//You can continue to add a new key value pair
$.ajax ({
 URL: '/upload ',
 type: ' POST '
 ) on the basis of existing form data. Cache:false,
 data:new FormData ($ (' #uploadForm ') [0]),
 processdata:false,
 contenttype:false
}). Done (function (res) {}). Fail (function (res) {});

Attention:

    • The Ajax ProcessData is set to false. Because the data value is a Formdata object, you do not need to work with it.
    • The second way <form> tag plus Enctyp e= "Multipart/form-data" attribute.
    • The cache is set to False and the upload file does not need to be cached.
    • ContentType set to False. This is set to false because it is a Formdata object constructed by the <form> form, and the property enctype= "Mutipart/form-data" has been declared.

After the front end is finished, the rest is the back end processing. OK, it's over here.

Formdata object, you can use a series of key-value pairs to simulate a complete form, and then use the XMLHttpRequest to send this "form."

The Formdata object is used on the Mozilla Developer website for detailed Formdata object usage instructions.

But the upload file part only the bottom of the XMLHttpRequest object send upload request, then how to upload through jquery ajax?

This article describes using the Formdata object to upload files through jquery.

Uploading files using <form> form initialization Formdata objects

HTML code

<form id= "Uploadform" enctype= "Multipart/form-data" > <input "File" id= "file"
 type= "file" name=
 <button id= "Upload" type= "button" >upload</button>
</form>

JavaScript code

$.ajax ({
 URL: '/upload ',
 type: ' POST ',
 cache:false,
 data:new FormData ($ (' #uploadForm ') [0]),
 Processdata:false,
 contenttype:false
}). Done (function (res) {
}). Fail (function (res) {});

Here are some points to note:

    • ProcessData set to False. Because the data value is a Formdata object, you do not need to work with it.
    • <form> tag to add the enctype= "Multipart/form-data" attribute.
    • The cache is set to False and the upload file does not need to be cached.
    • ContentType set to False. This is set to false because it is a Formdata object constructed by the <form> form, and the property enctype= "Multipart/form-data" has been declared.

After uploading, the server-side code needs to get the file input stream object from the query parameter name, because name= "file" is declared in <input>.

What if you don't construct a Formdata object with a <form> form?

Add a field by using the Formdata object to upload a file

HTML code

<div id= "Uploadform" >
 <input id= "file" type= "file"/> <button "id=" Upload "button
 " > Upload</button>
</div>

There is no <form> tag and there is no enctype= "Multipart/form-data" attribute.

JavaScript code

var formData = new FormData ();
Formdata.append (' file ', $ (' #file ') [0].files[0]);
$.ajax ({
 URL: '/upload ',
 type: ' POST ',
 cache:false,
 data:formdata,
 processdata:false,
 Contenttype:false
}). Done (function (res) {
}). Fail (function (res) {});

Here are a few different places:

    • The second argument for append () should be a file object, that is $ (' #file ') [0].files[0].
    • ContentType also set to ' false '.

You can see from code $ (' #file ') [0].files[0] that a <input type= "file" > tag can upload multiple files, just <input type= "file" > Add the multiple or multiple= "multiple" attribute.

Server-side Read files

Starting with Servlet 3.0, you can get uploaded files through the Request.getpart () or Request.getpars () two interfaces.

Here is not much to say, please refer to the official website tutorial uploading Files with Java Servlet Technology and sample the FileUpload Example application

The above is the entire content of this article, I hope to help you learn, but also hope that we support the cloud habitat community.

Related Article

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.