问题
I'm trying to send array files using JS. My code:
var formData = new FormData();
formData.append("files", files);
$.ajax({
url: './upload.php',
method: 'post',
data: formData,
processData: false,
contentType: false,
success: function(response) {
alert('Files uploaded successfully. ');
console.log(response);
},
error: function(jqXHR, textStatus, errorThrown) {
console.log(textStatus, errorThrown);
}
});
In this image you can see the response(red) from php https://beta.ctrlv.cz/mUwx and also you can see the files array data. My php code is:
<?php
echo $_POST['files'][0]["name"];
?>
I want use php script for upload, but the ajax didn't sent the array of file, which is important for uploading.
回答1:
Here's an answer that I found:
var data = new FormData();
jQuery.each(jQuery('#file')[0].files, function(i, file) {
data.append('file-'+i, file);
});
So now you have a FormData
object, ready to be sent along with the XMLHttpRequest.
jQuery.ajax({
url: 'php/upload.php',
data: data,
cache: false,
contentType: false,
processData: false,
type: 'POST',
success: function(data){
alert(data);
}
});
Here the source: https://stackoverflow.com/a/5976031/7282094
Hope that help.
回答2:
Change contentType: false,
to contentType: "multipart/form-data",
possibly.
Taken from http://api.jquery.com/jquery.ajax/
contentType (default: 'application/x-www-form-urlencoded; charset=UTF-8') Type: Boolean or String When sending data to the server, use this content type. Default is "application/x-www-form-urlencoded; charset=UTF-8", which is fine for most cases. If you explicitly pass in a content-type to $.ajax(), then it is always sent to the server (even if no data is sent). As of jQuery 1.6 you can pass false to tell jQuery to not set any content type header. Note: The W3C XMLHttpRequest specification dictates that the charset is always UTF-8; specifying another charset will not force the browser to change the encoding. Note: For cross-domain requests, setting the content type to anything other than application/x-www-form-urlencoded, multipart/form-data, or text/plain will trigger the browser to send a preflight OPTIONS request to the server.
来源:https://stackoverflow.com/questions/44087239/sending-filelist-using-ajax-to-php-script