This article mainly introduces the sample code of JavaScript using Ajax to upload files, and introduces the two upload methods in detail. Interested friends can learn about it
This article introduces the method of JavaScript using Ajax to upload files. The sample code is shared with everyone, as follows:
There are two main ways to upload files:
Use the form form to submit and upload the
html code as follows:
<form id="uploadForm" enctype="multipart/form-data"> <input id="file" type="file" name="file"/> <button id="upload" type="button">上传</button> </form>
The JavaScript code at this time is as follows:
var formData = new FormDate($('#uploadForm')[0]); $.ajax({ url: 'http://10.10.2.254:8080/file/associateupload', type: 'POST', cache: false, data: formData, processData: false, contentType: false, success:function(res){ console.log(res); } });
Note:
processData is set to false. Because the data value is a FormData object, there is no need to process the data.
cache is set to false, and uploading files does not require caching.
contentType is set to false. Because it is a FormData object constructed from the
Use the FormData object to add fields to upload files
The html code is as follows:
<p id="uploadp"> <input id="file" type="file"/> <button id="upload" type="button">上传</button> </p>
JavaScript is implemented as follows:
var formData = new FormData(); formData.append('file', $('#file')[0].files[0]); $.ajax({ url: '/upload', type: 'POST', cache: false, data: formData, processData: false, contentType: false, success:function(res){ console.log(res); }
There are several differences here:
The second parameter of append() should It is a file object, that is, $('#file')[0].files[0]. contentType also needs to be set to false.
You can see from the code $('#file')[0].files[0] that an tag can upload multiple files , just add multiple or multiple="multiple" attributes in .
The above is the detailed content of Introduction to how JavaScript uses Ajax to upload files. For more information, please follow other related articles on the PHP Chinese website!