2016-04-27 90 views
0

我嘗試在我的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); 
    } 
} 
+0

http://stackoverflow.com/questions/36281248/upload-image- to-database-in-laravel-5-using-eloquent-orm – Sunil

+0

@Sunil我試圖做到這一點,但我在這行'data:new FormData($(「#upload_form」)[0])中得到了一個jQuery錯誤, '錯誤是:'TypeError:'append'對一個沒有實現接口FormData的對象調用。' –

回答

0

你忘了CSRF驗證。

就此請求而言,您還必須發送CSRF令牌,或者至少禁用此路由的檢查。

轉到app/Http/Middleware/VerifyCsrfToken.php

和您的POST-網址添加到protected $except = [];

而且閱讀文檔的這一部分:https://laravel.com/docs/master/routing#csrf-protection

+0

是的,我也發送它ck我的html表單:'> –

+0

您有任何錯誤消息或日誌記錄嗎? – Dinar

+0

沒有得到一個空的對象我在ajax的錯誤函數上獲取錯誤,但沒有錯誤數據包含的是空的對象 –