Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to upload a file using jQuery.ajax and FormData

When I use XMLHttpRequest, a file is correctly uploaded using FormData. However, when I switch to jQuery.ajax, my code breaks.

This is the working original code:

function uploadFile(blobFile, fileName) {     var fd = new FormData();     fd.append("fileToUpload", blobFile);     var xhr = new XMLHttpRequest();     xhr.open("POST", "upload.php", true);     xhr.send(fd); } 

Here is my unsuccessful jQuery.ajax attempt:

function uploadFile(blobFile, fileName) {     var fd = new FormData();     fd.append("fileToUpload", blobFile);     var xm = $.ajax({         url: "upload.php",         type: "POST",         data: fd,     }); } 

What am I doing wrong? How can I get the file to be uploaded correctly, using AJAX?

like image 488
Harts Avatar asked Mar 08 '12 18:03

Harts


People also ask

How do I upload a file to FormData?

You can upload the selected file by creating a FormData class and passing it to Axios' post() function. const input = document. querySelector('#my-input'); const formData = new FormData(); formData. append('myFile', input.

Can we upload file using AJAX?

File upload is not possible through AJAX. You can upload file, without refreshing page by using IFrame .

How do you send a file using multipart form data?

Follow this rules when creating a multipart form: Specify enctype="multipart/form-data" attribute on a form tag. Add a name attribute to a single input type="file" tag. DO NOT add a name attribute to any other input, select or textarea tags.


1 Answers

You have to add processData:false,contentType:false to your method, so that jQuery does not alter the headers or data (which breaks your current code).

function uploadFile(blobFile, fileName) {     var fd = new FormData();     fd.append("fileToUpload", blobFile);      $.ajax({        url: "upload.php",        type: "POST",        data: fd,        processData: false,        contentType: false,        success: function(response) {            // .. do something        },        error: function(jqXHR, textStatus, errorMessage) {            console.log(errorMessage); // Optional        }     }); }   
like image 186
Rob W Avatar answered Sep 27 '22 22:09

Rob W