Laravel AJAX图片上传
试图让AJAX图像上传工作在Laravel 4上但有问题。
这就是我所拥有的:
表格:
{{ Form::open(array('class' => 'update-insertimage-form', "files" => true,)) }} {{ Form::file('image', array('class' => 'update-insertimage-btn', 'name' => 'update-insertimage-btn')) }} {{ Form::close() }}
和PHP:
$createImage = Image::make(Input::file('update-insertimage-btn'))->orientate(); $createImage->resize(600, null, function ($constraint) { $constraint->aspectRatio(); }); $createImage->save("user_uploads/cover_images/TEST.jpeg");
jQuery的:
$('.update-insertimage-form').submit(function() { $(".submit-newupdate-btn").addClass('disabled'); var rootAsset = $('.rootAsset').html(); $.ajax({ url: rootAsset+'saveUploadedImage', type: 'post', cache: false, dataType: 'json', data: $('.update-insertimage-form').serialize(), beforeSend: function() { }, success: function(data) { if(data.errors) { $('.modal-body').append('
'); } else if (data.success) { $(".form-control-addupdate").append(data.name); } }, error: function(xhr, textStatus, thrownError) { alert('Something went to wrong.Please Try again later...'); } }); return false; });
我使用相同的精确代码,其中哪些工作正常但不适用于AJAX。
错误是这样的:
{"error":{"type":"Intervention\\Image\\Exception\\NotReadableException","message":"Image source not readable","file":"\/Applications\/MAMP\/htdocs\/buildsanctuary\/vendor\/intervention\/image\/src\/Intervention\/Image\/AbstractDecoder.php","line":257}}
有帮助吗?
注意,尝试使用formData并将jQuery更改为:
$('.update-insertimage-form').submit(function() { $(".submit-newupdate-btn").addClass('disabled'); var rootAsset = $('.rootAsset').html(); var formData = new FormData(); formData.append('update-insertimage-btn[]', $('.update-insertimage-btn')[0].files[0], $('.update-insertimage-btn')[0].files[0].name); $.ajax({ url: rootAsset+'saveUploadedImage', type: 'post', cache: false, dataType: 'json', data: formData, processData: false, contentType: false, beforeSend: function() { }, success: function(data) { if(data.errors) { $('.modal-body').append('
'); } else if (data.success) { $(".form-control-addupdate").append(data.name); } }, error: function(xhr, textStatus, thrownError) { alert('Something went to wrong.Please Try again later...'); } }); return false; });
但这就是抛出错误:
{"error":{"type":"ErrorException","message":"preg_match() expects parameter 2 to be string, array given","file":"\/Applications\/MAMP\/htdocs\/buildsanctuary\/vendor\/intervention\/image\/src\/Intervention\/Image\/AbstractDecoder.php","line":208}}
谢谢你的帮助。
尝试将表单传递给FromData构造函数,而不是尝试手动将文件添加到它。
var formData = new FormData($('.update-insertimage-form')[0]);