Home Web Front-end JS Tutorial Using FormData to upload files with Ajax

Using FormData to upload files with Ajax

Apr 03, 2018 pm 05:27 PM
ajax formdata upload

This time I will bring you the use of FormData to upload files through Ajax. What are the precautions for using FormData to upload files through Ajax? The following is a practical case, let's take a look.

Upload files through traditional form submission:

Html code

<form id= "uploadForm" action= "http://localhost:8080/cfJAX_RS/rest/file/upload" method= "post" enctype ="multipart/form-data"> 
   <h1 >测试通过Rest接口上传文件 </h1> 
   <p >指定文件名: <input type ="text" name="filename" /></p> 
   <p >上传文件: <input type ="file" name="file" /></p> 
   <p >关键字1: <input type ="text" name="keyword" /></p> 
   <p >关键字2: <input type ="text" name="keyword" /></p> 
   <p >关键字3: <input type ="text" name="keyword" /></p> 
   <input type ="submit" value="上传"/> 
</form>
Copy after login
However, traditional form submission will cause the page to refresh, but In some cases, we do not want the page to be refreshed. In this case, we all use Ajax to make requests:

Js code

$.ajax({ 
   url : "http://localhost:8080/STS/rest/user", 
   type : "POST", 
   data : $( '#postForm').serialize(), 
   success : function(data) { 
     $( '#serverResponse').html(data); 
   }, 
   error : function(data) { 
     $( '#serverResponse').html(data.status + " : " + data.statusText + " : " + data.responseText); 
   } 
});
Copy after login
As above, through $('#postForm').serialize() can serialize the form, thereby passing all parameters in the form to the server.

However, in the above method, only general parameters can be passed, and the file stream of the uploaded file cannot be serialized and passed.

However, now mainstream browsers have begun to support an object called FormData. With this FormData, we can easily use Ajax to upload files
.

About FormData and its usageWhat is FormData? Let's take a look at the introduction on Mozilla.

XMLHttpRequest Level 2 adds a new interface FormData. Using the FormData object, we can use

JavaScript

to simulate a series of form controls with some key-value pairs. We can also use XMLHttpRequest's send () method to asynchronously submit this "form". Compared with ordinary ajax, the biggest advantage of using FormData is that we can upload a binary file asynchronously. Newer versions of all major browsers already support this Objects, such as Chrome 7+, Firefox 4+, IE 10+, Opera 12+, Safari 5+.

See:

https://

developer.mozilla.org/zh-CN/docs/Web/API/XMLHttpRequest/FormDataOnly one form passed from is shown here How to initialize FormData

<form enctype="multipart/form-data" method="post" name="fileinfo">
Copy after login

Js code

var oData = new FormData(document.forms.namedItem("fileinfo" )); 
oData.append( "CustomField", "This is some extra data" ); 
var oReq = new XMLHttpRequest(); 
oReq.open( "POST", "stash.php" , true ); 
oReq.onload = function(oEvent) { 
   if (oReq.status == 200) { 
     oOutput.innerHTML = "Uploaded!" ; 
   } else { 
     oOutput.innerHTML = "Error " + oReq.status + " occurred uploading your file.<br \/>"; 
   } 
}; 
oReq.send(oData);
Copy after login
See: https://developer.mozilla.org/zh-CN/docs/Web/Guide/Using_FormData_Objects

Use FormData, make Ajax requests and upload files

JQuery is used here, but older versions of JQuery such as 1.2 are not supported. It is best to use 2.0 or newer versions:

Html code

<form id= "uploadForm"> 
   <p >指定文件名: <input type="text" name="filename" value= ""/></p > 
   <p >上传文件: <input type="file" name="file"/></ p> 
   <input type="button" value="上传" onclick="doUpload()" /> 
</form>
Copy after login

Js code

function doUpload() { 
   var formData = new FormData($( "#uploadForm" )[0]); 
   $.ajax({ 
     url: 'http://localhost:8080/cfJAX_RS/rest/file/upload' , 
     type: 'POST', 
     data: formData, 
     async: false, 
     cache: false, 
     contentType: false, 
     processData: false, 
     success: function (returndata) { 
       alert(returndata); 
     }, 
     error: function (returndata) { 
       alert(returndata); 
     } 
   }); 
}
Copy after login
I believe you have mastered the method after reading the case in this article. For more exciting information, please pay attention to php Chinese website Other related articles!

Recommended reading:

js+ajaxcap operates the json object and loops it to the table for storage


Use ajax to verify registered users Whether the name exists


Ajax operation form asynchronously uploads files

The above is the detailed content of Using FormData to upload files with Ajax. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

How to upload lyrics to QQ Music How to upload lyrics to QQ Music Feb 23, 2024 pm 11:45 PM

With the advent of the digital age, music platforms have become one of the main ways for people to obtain music. However, sometimes when we listen to songs, we find that there are no lyrics, which is very disturbing. Many people hope that lyrics can be displayed when listening to songs to better understand the content and emotions of the songs. QQ Music, as one of the largest music platforms in China, also provides users with the function of uploading lyrics, so that users can better enjoy music and feel the connotation of the songs. The following will introduce how to upload lyrics on QQ Music. first

How to solve the 403 error encountered by jQuery AJAX request How to solve the 403 error encountered by jQuery AJAX request Feb 20, 2024 am 10:07 AM

Title: Methods and code examples to resolve 403 errors in jQuery AJAX requests. The 403 error refers to a request that the server prohibits access to a resource. This error usually occurs because the request lacks permissions or is rejected by the server. When making jQueryAJAX requests, you sometimes encounter this situation. This article will introduce how to solve this problem and provide code examples. Solution: Check permissions: First ensure that the requested URL address is correct and verify that you have sufficient permissions to access the resource.

Simple steps to upload your own music on Kugou Simple steps to upload your own music on Kugou Mar 25, 2024 pm 10:56 PM

1. Open Kugou Music and click on your profile picture. 2. Click the settings icon in the upper right corner. 3. Click [Upload Music Works]. 4. Click [Upload Works]. 5. Select the song and click [Next]. 6. Finally, click [Upload].

PHP and Ajax: Building an autocomplete suggestion engine PHP and Ajax: Building an autocomplete suggestion engine Jun 02, 2024 pm 08:39 PM

Build an autocomplete suggestion engine using PHP and Ajax: Server-side script: handles Ajax requests and returns suggestions (autocomplete.php). Client script: Send Ajax request and display suggestions (autocomplete.js). Practical case: Include script in HTML page and specify search-input element identifier.

How to solve jQuery AJAX request 403 error How to solve jQuery AJAX request 403 error Feb 19, 2024 pm 05:55 PM

jQuery is a popular JavaScript library used to simplify client-side development. AJAX is a technology that sends asynchronous requests and interacts with the server without reloading the entire web page. However, when using jQuery to make AJAX requests, you sometimes encounter 403 errors. 403 errors are usually server-denied access errors, possibly due to security policy or permission issues. In this article, we will discuss how to resolve jQueryAJAX request encountering 403 error

How to improve computer upload speed How to improve computer upload speed Jan 15, 2024 pm 06:51 PM

Upload speed becomes very slow? I believe this is a problem that many friends will encounter when uploading things on their computers. If the network is unstable when using a computer to transfer files, the upload speed will be very slow. So how can I increase the network upload speed? Below, the editor will tell you how to solve the problem of slow computer upload speed. When it comes to network speed, we all know that the speed of opening web pages, download speed, and upload speed are also very critical. Especially some users often need to upload files to the network disk, so a fast upload speed will undoubtedly save you a lot of money. Less time, what should I do if the upload speed is slow? Below, the editor brings you pictures and texts on how to deal with slow computer upload speeds. How to solve the problem of slow computer upload speed? Click "Start--Run" or "Window key"

How to solve the problem of jQuery AJAX error 403? How to solve the problem of jQuery AJAX error 403? Feb 23, 2024 pm 04:27 PM

How to solve the problem of jQueryAJAX error 403? When developing web applications, jQuery is often used to send asynchronous requests. However, sometimes you may encounter error code 403 when using jQueryAJAX, indicating that access is forbidden by the server. This is usually caused by server-side security settings, but there are ways to work around it. This article will introduce how to solve the problem of jQueryAJAX error 403 and provide specific code examples. 1. to make

How to get variables from PHP method using Ajax? How to get variables from PHP method using Ajax? Mar 09, 2024 pm 05:36 PM

Using Ajax to obtain variables from PHP methods is a common scenario in web development. Through Ajax, the page can be dynamically obtained without refreshing the data. In this article, we will introduce how to use Ajax to get variables from PHP methods, and provide specific code examples. First, we need to write a PHP file to handle the Ajax request and return the required variables. Here is sample code for a simple PHP file getData.php:

See all articles