图片上传无法通过ajax Laravel工作

问题描述 投票:0回答:3

有一个奇怪的问题,我确定它与我的脚本抓取文件输入字段的值的方式有关。

我知道控制器功能有效,因为我已经能够通过手动提交表单而不使用ajax来实现。

我也知道ajax在发送和接收请求时起作用,因为我通过修改它来测试它来解析一个有效的字符串来回。

此外,我可以看到脚本正在抓取文件,因为当我选择文件时,它会在控制台中显示所选文件。

在我的浏览器中,我得到500错误,在Laravel我只得到这个:

Symfony \ Component \ Debug \ Exception \ FatalThrowableError:在C:\ 123 \ app \ Http \ Controllers \ MyController.php中调用字符串上的成员函数getClientOriginalExtension():156

我已经尝试更新控制器以使用Request-> logo而不是成功。

视图:

<form enctype="multipart/form-data" class="form-horizontal" method="POST" action="{{ url('studio/uploadLogo') }}">
    {{ csrf_field() }}
    <div class="form-group{{ $errors->has('studioname') ? ' has-error' : '' }}">            
                <label for="imageInput" class="col-md-4 control-label">Logo</label>
                <div class="col-md-6">
                    <input data-preview="#preview" name="logo" type="file" id="imageInput">
                    <img id="preview" src="" style="display: none"></img>
                    <input class="form-control" type="submit">
                </div>
            </div>
        </form>

脚本:

$('#imageInput').change(function (e) {
    e.preventDefault();
    var logo = $('#imageInput').val();
    console.log(logo);
    $.ajax({
        type: "POST",
        url: '/studio/uploadLogo',
        data: {logo: logo},
        success: function( data ) {
            console.log(data);
        }
    });
}); 

控制器:

public function uploadLogo() {
    $file = Input::file('logo')->getRealPath();
    $photoName = str_random(20) . '.' . Input::file('logo')->getClientOriginalExtension();
    Input::get('logo')->move(public_path('avatars'), $photoName);
    $response = array(
        'status' => 'success',
        'data' => $photoName
    );
    return \Response::json($response);
}

路线:

 Route::post('/studio/uploadLogo', 'MyController@uploadLogo');
 Route::get('/studio/uploadLogo', 'MyController@uploadLogo');
javascript php ajax laravel
3个回答
1
投票

        You just change a view js script to submit like below
         $('.form-horizontal').submit(function(event){
            event.preventDefault();
            $.ajax({
                type        : 'POST',
                url         : "/studio/uploadLogo", 
                data        : new FormData(this),
                contentType:false,
                processData:false,
            })
            .done(function(data,status){
                 //Your codes here
             });
        });


        and
        echo string response from controller like below
    ----------------
          $file=$request->file('logo');
          $uploaded_file_path='';
          if($file!=null) {
              $destinationPath = 'uploads';
              $uploaded=$file->move($destinationPath,$file->getClientOriginalName());  
              $uploaded_file_path= $uploaded->getPathName();
               $response = array(
                    'status' => 'success',
                    'data' => $uploaded_file_path
                );
          }else{
              $response = array(
                  'status' => 'failed',
                  'data' => $uploaded_file_path
              );          
          }     
         echo json_encode($response);
    ----------------

1
投票

在你的控制器中尝试这个

public function uploadLogo() {
    $file = Input::file('logo')->getRealPath();
    $photoName = str_random(20) . '.' . Input::file('logo')->getClientOriginalExtension();
    Input::file('logo')->move(public_path('avatars'), $photoName);
    $response = array(
        'status' => 'success',
        'data' => $photoName
    );
    return \Response::json($response);
}

你给了

Input :: get('logo') - > move(public_path('avatars'),$ photoName);

请改成它

Input :: file('logo') - > move(public_path('avatars'),$ photoName);

你应该像ajax一样提交表格,就像@jalin评论一样(https://stackoverflow.com/a/47906201/4049692

希望这应该是问题。谢谢!。


0
投票

尝试在脚本代码中添加processData: false, contentType: false

$('#imageInput').change(function (e) {
e.preventDefault();
var logo = $('#imageInput').val();
var form_data = new FormData();
form_data.append("logo",$("#imageInput")[0].files[0]);
console.log(logo);
$.ajax({
    type: "POST",
    url: '/studio/uploadLogo',
    data: {form_data},
    cache : false,
    processData: false,
    contentType: false
    success: function( data ) {
        console.log(data);
    }
});
}); 

并尝试在$request->logo等控制器中获取值

请参阅我的答案enter link description here

© www.soinside.com 2019 - 2024. All rights reserved.