user1012181
user1012181

Reputation: 8726

File upload via Ajax in Laravel

I'm trying to upload a file through ajax in Laravel.

$("#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.

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?

Upvotes: 1

Views: 4110

Answers (1)

user1012181
user1012181

Reputation: 8726

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.

Upvotes: 1

Related Questions