【问题标题】:Laravel upload form returning jsonLaravel 上传表单返回 json
【发布时间】:2019-03-11 16:36:12
【问题描述】:

我仍然是 laravel 的初学者并坚持使用上传 ajax 表单:它仍在发送显示在浏览器中的 json 响应,而不是像我期望的那样停留在当前页面上。 我只想得到一个我可以在当前页面上使用的 json 响应。

这是我的看法

<form action="/Project/UploadDocumentProject" enctype="multipart/form-data"  method="post"  id ="form0">

    {{ csrf_field() }}

    <input id="ProjectID" name="ProjectID" type="hidden" value="{{$Project->id}}">

    <div class="form-group">
        <input name="DocumentFile" id="DocumentFile" class="form-control" type="file" >
    </div>


    <div class="form-group">
        <button id ="test" class="btn btn-success upload-image" type="submit">Upload</button>
    </div>

</form>

这是我的 ajax 请求

$('#form0').on("submit", function(e){
    e.preventDefault();
    $(this).ajaxForm(options);

    var options = { 
        complete: function(response) 
        {
            if($.isEmptyObject(response.responseJSON.error)){
                $("input[name='DocumentFile']").val('');
                alert('Image Upload Successfully.');
            }else{
                printErrorMsg(response.responseJSON.error);
            }
        }
    };

});

这是我的控制器

public function UploadDocumentProject (Request $Request)
{
    $ProjectID=$Request->get('ProjectID');
    $filename = $Request->DocumentFile->getClientOriginalName();

    $Request->DocumentFile->storeAs('/public/projects/'.$ProjectID.'/files',$filename);

    return response()->json(['success'=>'done']);

}

这是我的路线

Route::post('/Project/UploadDocumentProject','ProjectController@UploadDocumentProject');

我已经尝试在我的表单中指定 data-ajax="true" data-ajax-method="POST",但是即使在我的 ajax 请求中指定数据字段时,请求也不会考虑文件输入。 谁能帮助我?

谢谢! :)

【问题讨论】:

    标签: php ajax laravel upload


    【解决方案1】:

    在使用.ajaxForm(options)之前,您需要指定options。 我会在加载后直接配置它,而不是在提交处理程序中

    重做的 JS 代码:

    $.ready(function(){
        var options = { 
            complete: function(response)
            {
                if($.isEmptyObject(response.responseJSON.error)){
                    $("input[name='DocumentFile']").val('');
                    alert('Image Upload Successfully.');
                }else{
                    printErrorMsg(response.responseJSON.error);
                }
            }
        };
        $(this).ajaxForm(options);
    }};
    

    如果在没有目标后端 php 应用程序的情况下对其进行测试 - 但发送了包含文件的请求。因此,如果您遇到其他问题,请告诉我

    【讨论】:

    • 感谢您的帮助!但似乎我回到了我的问题:请求被发送到服务器但没有文件信息......
    • 好的,那么我们需要进行调试 :-) 您确定文件已发送到服务器吗? (你检查过你的浏览器开发工具——尤其是网络选项卡吗?)如果你确定请根据laravel.com/docs/5.7/filesystem#file-uploads更改你的php代码(我假设你使用的是最新的laravel版本)-$path = $Request-&gt;file('DocumentFile')-&gt;store('document');echo $path;
    • 其实不是。它发送一个请求,但带有项目 ID 输入但没有文件输入。所以服务器发回一个 500 响应,指定我在 null 上调用函数。
    • 那很糟糕:-/您使用的是哪个浏览器?它应该支持XMLHttpRequestcaniuse.com/#feat=xhr2
    • Chrome 69 和 firefox 62 都是最新的:/
    【解决方案2】:

    终于找到了如何制作正确的ajax文件格式

    这是我的做法

    查看

    <form action="{{ route('Project/UploadDocumentProject') }}"  method="post" id ="form0" enctype="multipart/form-data" >
    
            {{ csrf_field() }}
            <input id="ProjectID" name="ProjectID" type="hidden" value="{{$Project->id}}">
    
    
    
            <div class="form-group">
              <input name="fileAjax" id="fileAjax" class="form-control" type="file">test</textarea>  
            </div>
    
            <div class="form-group">
              <button id ="test" class="btn btn-success upload-image" type="submit" >Upload</button>
            </div>
    
    
    </form>
    

    Ajax 请求

    var files;
    
    
                     $('input[type=file]').on('change', prepareUpload);
    
    
                     function prepareUpload(event)
                     {
                        files = event.target.files;
                      }
                      $("#form0").submit(function (e) {
                        e.preventDefault();
                        var form = $("#form0");
                        var data = new FormData();
    
                        $.each(files, function(key, value)
                           {
                                data.append(key, value);
                            });
    
                        var $ProjectID = $('#ProjectID').val();
    
                         data.append('ProjectID', $ProjectID);
                        $.ajax({
                            type: "post",
                            url: form.attr('action'),
                            data: data,
                            processData: false,
                            contentType: false,
                            cache: false,
                            enctype: 'multipart/form-data',
                            headers: {
                                'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
                            },
    
    
                            success: function (data) {
                                //some code here...
                            }
                        });
                    });
    

    控制器

     public function UploadDocumentProject (Request $Request) {
    $path = $Request->file('0')->store('document');
    $filename = $Request->file('0')->getClientOriginalName();
    $Request->file('0')->storeAs('/public/projects/files',$filename);
    
      //some code here...
    
    return Response::json(array('var1'=>$val1 ,...));
    
    }
    

    路线

    Route::post('Project/UploadDocumentProject', ['as'=>'Project/UploadDocumentProject','uses'=>'ProjectController@UploadDocumentProject']);
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-09-04
      • 1970-01-01
      • 2021-11-04
      • 1970-01-01
      • 2018-07-27
      • 2016-10-26
      • 1970-01-01
      • 2014-10-26
      相关资源
      最近更新 更多