Formdata是空的 - laravel 5.4

时间:2017-05-18 11:23:20

标签: javascript php jquery ajax laravel-5.4

嗨朋友,
我正在尝试使用laravel 5.4中的ajax上传图像

问题
Formdata在服务器端是空的

代码

查看

<form role="form" action="{{route('auth.upload')}}" method="post" enctype="multipart/form-data" id="form3">
     {{ csrf_field() }}
     <h3>Upload Logo</h3>

     <div class="form-group">
          <label class="custom-file upload-image">
          <input type="file" id="image" name="image" class="custom-file-input">
          <span class="custom-file-control"></span>
          </label>
      </div>
      <button type="submit" class="btn btn-upload">Save Image</button>
</form>  

JS

$('#form3').on('submit',function(e){
    e.preventDefault();

    var url = $(this).attr('action'),
    post = $(this).attr('method'),
    data = new FormData(this);

    $.ajax({
        url: url,
        method: post,
        data: data,
        success: function(data){
            console.log(data);
        },
        error: function(xhr, status, error){
            alert(xhr.responseText);
        },
        processData: false,
        contentType: false
    });
});  

路线

Route::post('home/form3', 'HomeController@store')->name('auth.upload');  

控制器

public function store(Request $request){
    if ($request->ajax()) {

        return $request->all(); // THIS IS RETURNING EMPTY OBJECT

        if ($request->hasFile('image')) {

            $name = $request->image->getClientOriginalName();
            $request->image->storeAs('public/upload',$name);

            $company = new Company;
            $url = Storage::url($name);
            $company->update(['image'=>$url]);

            return response(['msg'=>'image uploaded']);
        }else{
            return response(['msg'=>'No file has selected']);
        } 
    }
}  

从服务器端返回响应是:

Object {_token: "zFKgoBkdjaIswMG5X0fOyVtaGSYMs84iPDtJA4F5", image: Object}
   image : Object
   _token : "zFKgoBkdjaIswMG5X0fOyVtaGSYMs84iPDtJA4F5"
   __proto__ : Object  

我只能看到令牌正在返回但没有上传图片的数据。如果我在不使用ajax的情况下提交表单,那么它工作正常。

如果在不使用ajax的情况下提交输出(这是我希望甚至使用ajax提交的输出):

array:2 [▼
  "_token" => "eVEjl9UW4rU69oz1lIIiuNABZVpRJFldDST02Nje"
  "image" => UploadedFile {#229 ▼
    -test: false
    -originalName: "empty-normal.png"
    -mimeType: "image/png"
    -size: 85494
    -error: 0
    #hashName: null
    path: "C:\xampp\tmp"
    filename: "php917E.tmp"
    basename: "php917E.tmp"
    pathname: "C:\xampp\tmp\php917E.tmp"
    extension: "tmp"
    realPath: "C:\xampp\tmp\php917E.tmp"
    aTime: 2017-05-18 11:17:11
    mTime: 2017-05-18 11:17:11
    cTime: 2017-05-18 11:17:11
    inode: 0
    size: 85494
    perms: 0100666
    owner: 0
    group: 0
    type: "file"
    writable: true
    readable: true
    executable: false
    file: true
    dir: false
    link: false
    linkTarget: "C:\xampp\tmp\php917E.tmp"

}     ]

任何人都可以帮我解决这个问题吗?

**感谢提前......

1 个答案:

答案 0 :(得分:0)

试试这个,它会对你有帮助。

$(document).on('submit', 'yourformId', function (event) {
    event.stopPropagation();
    event.preventDefault();
    var data = new FormData($(this)[0]);


    if (xhr && xhr.readyState !== 400 && xhr.status !== 200) {
        xhr.abort();
    }

    var xhr = $.ajax({
        url: "urltoUpload",
        method: "POST",
        cache: false,
        data: data,
        contentType: false, // NEEDED, DON'T OMIT THIS (requires jQuery 1.6+)
        processData: false, // NEEDED, DON'T OMIT THIS
        // dataType: 'json',
        statusCode: {
            404: function () {
                alert("status message")
            },
            500: function () {
                alert("server down");
            }
        },
        beforeSend: function (jqXHR, setting) {
            if (setting.status !== 200) {
                console.log("You can put here")
            }
        },
        error: function (jaXHR, textStatus, errorThrown) {
            // Now it will get parse error because dataType is json and response is html
            // console.log(errorThrown);
        },
        success: function (data, textStatus, jqXHR) {
            console.log(data);

            if (typeof data.error === 'undefined') {
                // Success so call function to process the form
                console.log('SUCCESS: ' + data.success);
            }
            else {
                // Handle errors here
                console.log('ERRORS: ' + data.error);
            }
        },
        complete: function (jqXHE, textStatus) {
            document.body.innerHTML = "dfafsaf";
        }

    });
});

在您的控制器中,您可以使用

dd($request->all());

确定!!