1

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?

10
  • Try getting the path before moving the file Commented Feb 17, 2015 at 17:25
  • The response is {"success":true,"uploaded":true,"url":"C:\\wamp\\tmp\\php7A29.tmp"} Commented Feb 17, 2015 at 17:26
  • And... that's not what you want? Commented Feb 17, 2015 at 17:27
  • I want to upload the file to a folder and return the URL to the ajax. Commented Feb 17, 2015 at 17:27
  • {"success":true,"uploaded":true,"url":"\/uploads\/2015\/02\/"} Commented Feb 17, 2015 at 17:34

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.