在Laravel中通过Ajax上传文件

时间:2015-02-17 17:23:08

标签: javascript jquery ajax laravel

我试图通过Laravel中的ajax上传文件。

$("#stepbutton2").click(function(){
            var uploadFile = document.getElementById("largeImage");
            if( ""==uploadFile.value){


            }
            else{
                var fd = new FormData();

                fd.append( "fileInput", $("#largeImage")[0].files[0]);

                $.ajax({
                    url: '/nominations/upload/image',
                    data: fd,
                    processData: false,
                    contentType: false,
                    type: 'POST',
                    success: function(data){
                        if(data.uploaded==true){
                            alert(data.url);
                        }
                    },
                    error: function(err){
                        alert(err);
                    }
                });

            }
        });

我将文件输入传递给php脚本。

public function image(){

$file = Input::file('fileInput');
    $ext = $file->getClientOriginalExtension();
    $fileName = md5(time()).".$ext";

    $destinationPath = "uploads/".date('Y').'/'.date('m').'/';
    $file->move($destinationPath, $fileName);
    $path = $file->getRealPath();
    return Response::json(["success"=>true,"uploaded"=>true, "url"=>$path]);


    }

我收到的回复是

{"success":true,"uploaded":true,"url":false}

请求有效负载

------WebKitFormBoundary30GMDJXOsygjL0ZS
Content-Disposition: form-data; name="fileInput"; filename="DSC06065 copy.jpg"
Content-Type: image/jpeg

为什么会这样?

1 个答案:

答案 0 :(得分:1)

找到答案:

 public function image(){

         $file = Input::file('fileInput');
             $ext = $file->getClientOriginalExtension();
             $fileName = md5(time()).".$ext";

             $destinationPath = "uploads/".date('Y').'/'.date('m').'/';
             $moved_file = $file->move($destinationPath, $fileName);
             $path = $moved_file->getRealPath();
             return Response::json(["success"=>true,"uploaded"=>true, "url"=>$path]);


             }

在将其分配给新变量后获取路径。