我一直在试图让AJAX的文件上传,因为前两天在lavavel 4个工作,我洙的运气了现在。
I've been trying to get ajax file upload working in lavavel 4 since last two days and I'm soo out of luck right now.
我的jQuery块
$(document).ready(function(){
$('#basicModuleImage').change(function () {
sendFile(this.files[0]);
});
function sendFile(file) {
$.ajax({
type: 'post',
url: '/upload',
data: file,
enctype: 'multipart/form-data',
success: function (data) {
alert(data);
},
processData: false,
contentType: file.type
});
}
});
HTML块
HTML block
<form method="post" action="">
<input type="file" id="basicModuleImage" name="basicModuleImage" />
</form>
LARAVEL PHP代码块
LARAVEL PHP block
Route::post('upload', function(){
return Response::json(array('a'=>var_dump(Input::all()),'b'=>var_dump($_FILES)));
});
我也尝试过使用 https://github.com/LPology/Simple-Ajax-Uploader < /一>,但它似乎是一个问题laravel。
I also tried using https://github.com/LPology/Simple-Ajax-Uploader but it seems a problem with laravel.
JSON响应返回A和B都为空。
JSON response returns a and b both null.
Actualy,您无法发送文件,在(基本)AJAX(XMLHtt prequest)。
Actualy, you cannot send files over (basic) AJAX (XMLHttpRequest).
您eighter需要使用一些IFRAME载,或XMLHtt prequest2。 我会去XHR2。 这里是code我与Laravel4使用部分的复制 - 粘贴,就像一个魅力
You eighter need to use some "iframe" uploader, or XMLHttpRequest2. I would go for XHR2. Here is copy-paste of portion of code I use with Laravel4, works like a charm
/**
* Read selected files locally (HTML5 File API)
*/
var filesToUpload = null;
function handleFileSelect(event)
{
var files = event.target.files || event.originalEvent.dataTransfer.files;
// Itterate thru files (here I user Underscore.js function to do so).
// Simply user 'for loop'.
_.each(files, function(file) {
filesToUpload.push(file);
});
}
/**
* Form submit
*/
function handleFormSubmit(event)
{
event.preventDefault();
var form = this,
formData = new FormData(form); // This will take all the data from current form and turn then into FormData
// Prevent multiple submisions
if ($(form).data('loading') === true) {
return;
}
$(form).data('loading', true);
// Add selected files to FormData which will be sent
if (filesToUpload) {
_.each(filesToUpload, function(file){
formData.append('cover[]', file);
});
}
$.ajax({
type: "POST",
url: 'url/to/controller/action',
data: formData,
processData: false,
contentType: false,
success: function(response)
{
// handle response
},
complete: function()
{
// Allow form to be submited again
$(form).data('loading', false);
},
dataType: 'json'
});
}
/**
* Register events
*/
$('#file-input').on('change', handleFileSelect);
$('form').on('submit', handleFormSubmit);