【问题标题】:Fail to upload image using Ajax on Laravel 5在 Laravel 5 上使用 Ajax 上传图片失败
【发布时间】:2016-08-21 10:34:14
【问题描述】:

我尝试在我的 laravel 项目上创建一个使用 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','ProfileFormsController@postImage');

控制器

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);
    }
}

【问题讨论】:

  • @Sunil 我尝试这样做,但我在这一行中得到一个 jQuery 错误data:new FormData($("#upload_form")[0]), 错误是:TypeError: 'append' called on an object that does not implement interface FormData.

标签: php jquery ajax laravel laravel-5


【解决方案1】:

您忘记了 CSRF 验证。

只要此请求是 POST,您还必须发送 CSRF 令牌,或者至少禁用对该路由的检查。

转到app/Http/Middleware/VerifyCsrfToken.php

并将您的 POST-url 添加到 protected $except = [];

另请阅读这部分文档:https://laravel.com/docs/master/routing#csrf-protection

【讨论】:

  • 是的,我也发送它检查我的 html 表单:&lt;input type="hidden" name="_token" id="_token" value="{{csrf_token() }}"&gt;
  • 没有得到一个空对象我在 ajax 的错误函数上获取错误但没有错误数据包含是空对象
  • 但是根据代码,你不返回任何东西,所以你不会有任何数据从后端返回。如果确实是返回 500 之类的错误,还要检查日志文件。
  • 在哪里可以找到 laravel 的日志文件?
猜你喜欢
  • 2019-06-30
  • 2016-04-11
  • 2017-09-28
  • 2020-07-04
  • 1970-01-01
  • 2018-12-15
  • 2020-01-11
  • 2017-06-04
  • 1970-01-01
相关资源
最近更新 更多