我嘗試在我的laravel項目上創建一個使用ajax在服務器上傳圖片的表單,但請求總是失敗,我嘗試這樣做是否存在代碼中的任何問題?在Laravel 5上使用Ajax上傳圖片失敗
HTML:
<form id="changeImage" enctype="multipart/form-data">
<input type="hidden" name="_token" id="_token" value="{{csrf_token() }}">
<center>
<div class="form-group">
<center><input type="file" name="image" accept="image/*"></center>
<p class="help-block">Format: png, jpg et gif.</p>
</div>
</center>
<button type="submit" class="btn btn-primary">Submit</button>
</form>
阿賈克斯:
$('input[name="image"]').change(function(event) {
files = event.target.files;
});
$('#changeImage').submit(function(event) {
event.preventDefault();
var _token= $('input[name="_token"]').val();
var data = new FormData();
data.append('_token',_token);
$.each(files, function(k, v) {
data.append('image',v);
});
$.ajax({
url: '/profile/image',
type: 'POST',
data:data,
processData: false,
contentType: "multipart/form-data",
success: function(data){
console.log('done'+data);
},
async: false,
error: function(data){
console.log('No');
var errors = data.responseJSON;
errorsHtml = '<div class="alert alert-danger"><ul>';
$.each(errors , function(key, value) {
errorsHtml += '<li>' + value[key] + '</li>';
});
errorsHtml += '</ul></div>';
$('#form-errors').html(errorsHtml);
}
});
});
服務器端 - PHP(laravel):
路線:
Route::post('profile/image','[email protected]');
控制器
public function postImage(Request $request){
if($request->ajax()){
$imagedestination = 'images\profile';
$file = $request->file('image');
$image_name = time()."-".$file->getClientOriginalName();
$file->move($imagedestination, $image_name);
}
}
http://stackoverflow.com/questions/36281248/upload-image- to-database-in-laravel-5-using-eloquent-orm – Sunil
@Sunil我試圖做到這一點,但我在這行'data:new FormData($(「#upload_form」)[0])中得到了一個jQuery錯誤, '錯誤是:'TypeError:'append'對一個沒有實現接口FormData的對象調用。' –