HOW TO SEND MULTIPART/FORMDATA WITH JQUERY AND AJAX?

How can I sover multipart FormData using JQuery.ajax? I know it’s possible khổng lồ vị it, but the code I have below, is returning NULL on my server side. I have sầu no clue why that is happening at all.I am trying khổng lồ upload a các mục of files to lớn the server side using the code below:

$.ajax( type: "POST", cache: false, contentType: "multipart/form-data", processData: false, url: "localhost:2458/backend/upload.php", data: $("#fileInputBox").attr("files"), success: function(data) alert("Data sending was successful"); );Any help would be appreciated.Thanks


3 Likes
akhông tính phí (afree) August 31, năm nhâm thìn, 1:10am #2

Starting with Safari 5/Firefox 4, it’s easiest to use the FormData class:

var data = new FormData();jQuery.each(jQuery("#file")<0>.files, function(i, file) data.append("file-"+i, file););So now you have sầu a FormData object, ready khổng lồ be sent along with the XMLHttpRequest.

Bạn đang xem: How to send multipart/formdata with jquery and ajax?

jQuery.ajax( url: "php/upload.php", data: data, cache: false, contentType: false, processData: false, type: "POST", success: function(data) alert(data); );It’s imperative sầu that you set the contentType option khổng lồ false, forcing jQuery not to add a Content-Type header for you, otherwise, the boundary string will be missing from it. Also, you must leave the processData flag phối to false, otherwise, jQuery will try to convert your FormData inkhổng lồ a string, which will fail.

You may now retrieve the tệp tin in PHPhường using:

$_FILES<‘file-0’>

(There is only one tệp tin, file-0, unless you specified the multiple attribute on your tệp tin input đầu vào, in which case, the numbers will increment with each tệp tin.)

Using the FormData emulation for older browsers

var opts = url: "php/upload.php", data: data, cache: false, contentType: false, processData: false, type: "POST", success: function(data) alert(data); ;if(data.fake) // Make sure no text encoding stuff is done by xhr opts.xhr = function() var xhr = jQuery.ajaxSettings.xhr(); xhr.send = xhr.sendAsBinary; return xhr; opts.contentType = "multipart/form-data; boundary="+data.boundary; opts.data = data.toString();jQuery.ajax(opts);Create FormData from an existing form

Instead of manually iterating the files, the FormData object can also be created with the contents of an existing size object:

var data = new FormData(jQuery("form")<0>);Use a PHPhường native sầu array instead of a counter

Just name your tệp tin elements the same và over the name in brackets:

jQuery.each(jQuery("#file")<0>.files, function(i, file) data.append("file<>", file););$_FILES<"file"> will then be an array containing the tệp tin upload fields for every tệp tin uploaded. I actually recommkết thúc this over my initial solution as it’s simpler to iterate over.

Xem thêm: Cách Nấu Cháo Đậu Xanh Dành Cho Bé Yêu Ăn Dặm, Học Ngay #2


I believe you better just vì it using HTML? that’s the easiest way I know to upload a series of files to lớn your backover VPS, but Javascript is possible as well. Here is how you can bởi it:

1. Using Pure HTML Form

1.1 Frontend

1.2 Backend

The HTML size above, will produce the following data structure at the PhP. VPS backend (this is just sample data):

Array media:Array name:Array /* List of tệp tin names, under the name array. */ <0> => MyTextFile.txt <1> => HelloWorld.png <2> => HelloWorld.csv type:Array <0> => text/plain <1> => image/png <2> => text/plain tmp_name:Array <0> => /tmp/someBlahBlahBlah1 <1> => /tmp/someBlahBlahBlah2 <1> => /tmp/someBlahBlahBlah3 error:Array <0> => 0 <1> => 0 <2> => 0 size:Array <0> => 785459 <1> => 784512 <1> => 885421 /* end of truyền thông media array */ /* kết thúc of root array */##2. Using JQuery.Ajax

2.1. Frontend JQuery.Ajax

Apparently the mistake in your code sneppit is that you’ve been sending out the files in the same format you get them through $("#fileInputBox").attr("files"), which is completely wrong:


*
summerbreeze384:

`data: $("#fileInputBox").attr("files"),`Instead you should be doing, is first generating a FormData based on the files the user picked to lớn upload, and then sending out that FormData to the hệ thống backover, something as follows should vày the trick:

var form_data = new FormData($("input"));/* First build a FormData of files khổng lồ be sent out to the server-side */jQuery.each($("input")<0>.files, function(i, file) form_data.append(i, file););/* Now send the gathered files data to lớn our backend server */iQuery.ajax( type: "POST", cache: false, processData: false, contentType: false, data: form_data, url: "/backend/upload.php", success: function(data) /* The data has been sent out successfully. */ );

2.2. PhPhường. Backend

For the Ajax code snippet above, the PhP backend VPS $_FILES global variable, would be structured and a totally different way, so make sure khổng lồ notice that. Here is a sample data structure you’ll be receiving on the server-end:

Array <0> => Array name => MyTxtFile.txt type => plain/text tmp_name => /tmp/generated_name_here error => 0 /* error code, if the upload failed. */ kích cỡ => 777474 ..... <999> => Array name => MyJpgImage.jpg type => image/jpeg tmp_name => /tmp/generated_name_here2 /* this is the hệ thống location of the tệp tin on your backover if the upload has been successful */ error => 0 kích cỡ => 85474 When comparing the two structures together (the one we recieved using the HTML khung, và the Ajax call), you’ll notice that the ajax Call using a FormData tends to lớn cluster every file’s attributes inlớn a single array, rather than having them all split around within different arrays. Which can be counted as a plus in many cases & makes the files array easier lớn browse.

That’s it, Hope that helps you out.


Your ajax file should look something lượt thích this:

$(document).ready(function (e) $("#form").on("submit",(function(e) e.preventDefault(); $.ajax( url: "ajaxupload.php", type: "POST", data: new FormData(this), contentType: false, cache: false, processData:false, beforeSover : function() //$("#preview").fadeOut();$("#err").fadeOut(); , success: function(data) if(data=="invalid") // invalid tệp tin format. $("#err").html("Invalid File !").fadeIn();else // view uploaded tệp tin. $("#preview").html(data).fadeIn(); $("#form")<0>.reset(); , error: function(e) $("#err").html(e).fadeIn(); ); )););Source: PHP File Upload with Ajax