Using FormData to upload files with Ajax
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>
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); } });
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
JavaScriptto 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">
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);
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>
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);
}
});
}
Recommended reading:
js+ajaxcap operates the json object and loops it to the table for storageUse ajax to verify registered users Whether the name existsAjax operation form asynchronously uploads filesThe 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!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

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

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics

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

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.

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].

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.

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

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 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

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:
