Uploading files using FormData objects through jQuery Ajax

The FormData object can simulate a complete form using a series of key value pairs, and then send the “form” using XML HttpRequest.

There are detailed instructions for using FormData objects on the Mozilla Developer website.

But in the file upload section, only the underlying XMLHttpRequest object sends the upload request, so how can we upload it through jQuery’s Ajax?

This article will introduce using the FormData object to upload files through jQuery.

Using th form to initialize the FormData object and upload files

  • HTML code

  • JavaScript code

Here are a few points to note:

  • Set processData to false. Because the data value is a FormData object, there is no need to process the data.
  • Add the enctype=”multipart/form data” attribute to the tag.
  • Cache is set to false, and uploading files does not require caching.
  • Set contentType to false. Because it is a FormData object constructed from theform and the attribute enctype=”multipart/form data” has already been declared, it is set to false here.

After uploading, the server-side code needs to use the query parameter name file to obtain the file input stream object, becausedeclares name=”file”.

What if we don’t use theform to construct a FormData object?

Upload files by adding fields using the FormData object

  • HTML code
  • JavaScript code

Server side file reading

Starting from Servlet 3.0, uploaded files can be obtained through two interfaces: request. getPart() or request. getPars().

Comments

No comments yet. Why don’t you start the discussion?

Leave a Reply

Your email address will not be published. Required fields are marked *