JQuery Ajax methods to upload files using Formdata objects _jquery

Source: Internet
Author: User

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.

Background Receive file:

 <bean id=" Multipartresolver "class=" Org.springframework.web.multipart.commons.CommonsMultipartResolver "> <property name=" defaultencoding "value = "Utf-8"/> </bean> @RequestMapping (value = "/import_tg_resource") public Modelandview Import_tg_resource (@ Requestparam (value = "File", Required = False) multipartfile[] files, httpservletrequest request, Modelmap model) {System
. OUT.PRINTLN ("Start bulk uploads: Number of files:" + files.length);
for (Multipartfile file:files) {String path = Request.getsession (). Getservletcontext (). Getrealpath ("Upload");
String fileName = File.getoriginalfilename ();
String prefix = filename.substring (Filename.lastindexof ("."));
FileName = new Date (). GetTime () + prefix;
SYSTEM.OUT.PRINTLN ("Save path" + path);
File TargetFile = new file (path, fileName);
if (!targetfile.exists ()) {targetfile.mkdirs ();} file.transferto (TargetFile); }
}

The above is a small set of jquery Ajax to introduce the use of Formdata object upload file method, I hope to help you, if you have any questions please give me a message, small series will promptly reply to everyone. Here also thank you very much for the cloud Habitat Community website support!

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.