0

Hi i am having a hard time using move_uploaded_file function to pass file to a new location. I am using ajax to pass function to my process.php. Hope you can help me.

Here is my process.php

    $target_dir = "../files-here/";
    $filename = $_POST['filename']; 
    $path_url = $target_dir .$filename;

    if (file_exists($path_url)) {
            echo "Sorry, file already exists.";
            $uploadOk = 0;
        }
        else
        {
            if(move_uploaded_file($filename, $path_url))
            echo "The file".$filename."has been uploaded";

Here is my form with ajax.

echo "<form method='post' enctype='multipart/form-data' id='test_ajax'>";

    echo "<input name='uploadedfile' type='file' id='custom-file-input' class='test-only' /><br/>";
    echo "</form>";
    echo '<button value="Upload" id="custom-submit-input">Upload</button>';


   <script>
jQuery('#custom-submit-input').click(function(){
          
var filename = jQuery('input[type=file]').val().replace(/.*(\/|\\)/, '');

           jQuery.post("file-here/process.php", {                   
                filename: filename

            }, function(data) {
                console.log(data);
                
            });  
   </script>
shadowbudz
  • 231
  • 1
  • 5
  • 17
  • You are just sending filename. You should send form data for uploading file. Check this out http://stackoverflow.com/questions/2320069/jquery-ajax-file-upload – iLaYa ツ Jul 21 '15 at 07:03

1 Answers1

0

I'm not sure that this will work as you expect. Your form never gets 'submitted', so your file doesn't get uploaded and you are not processing your uploaded file. You might manage to POST the filename of a file, but thats all.

You need to:

  1. Submit your form in the usual way (using HTML)
  2. Process your uploaded file (using PHP)
  3. Move your uploaded file (using PHP)

Your uploaded file will exist in a 'temporary' directory with a 'temporary' filename once uploaded, and you will need to get that data from the $_FILES array. You can use move_uploaded_file to move the temporary file to its final destination.

I'm not sure that you can 'ajax' much of this process.

MaggsWeb
  • 3,018
  • 1
  • 13
  • 23