简体   繁体   English

通过Laravel中的Ajax上传文件

[英]File upload via Ajax in Laravel

I'm trying to upload a file through ajax in 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);
                    }
                });

            }
        });

I'm passing the file input to the php script. 我将文件输入传递给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]);


    }

I'm getting a the response as 我得到一个回应

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

The request Payload is 请求有效负载为

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

Why this is happening? 为什么会这样呢?

Found the answer: 找到了答案:

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


             }

Get the path after assigning it to a new variable. 将路径分配给新变量后,获取路径。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM