Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery AJAX file upload PHP

I want to implement a simple file upload in my intranet-page, with the smallest setup possible.

This is my HTML part:

<input id="sortpicture" type="file" name="sortpic" /> <button id="upload">Upload</button> 

and this is my JS jquery script:

$("#upload").on("click", function() {     var file_data = $("#sortpicture").prop("files")[0];        var form_data = new FormData();     form_data.append("file", file_data);     alert(form_data);     $.ajax({         url: "/uploads",         dataType: 'script',         cache: false,         contentType: false,         processData: false,         data: form_data,                                  type: 'post',         success: function(){             alert("works");          }     }); }); 

There is a folder named "uploads" in the root directory of the website, with change permissions for "users" and "IIS_users".

When I select a file with the file-form and press the upload button, the first alert returns "[object FormData]". the second alert doesn't get called and the"uploads" folder is empty too!?

Can someone help my finding out whats wrong?

Also the next step should be, to rename the file with a server side generated name. Maybe someone can give me a solution for this, too.

like image 232
user2355509 Avatar asked Jun 01 '14 14:06

user2355509


People also ask

What is Move_uploaded_file in PHP?

Definition and Usage The move_uploaded_file() function moves an uploaded file to a new destination. Note: This function only works on files uploaded via PHP's HTTP POST upload mechanism. Note: If the destination file already exists, it will be overwritten.


2 Answers

**1. index.php** <body>     <span id="msg" style="color:red"></span><br/>     <input type="file" id="photo"><br/>   <script type="text/javascript" src="jquery-3.2.1.min.js"></script>   <script type="text/javascript">     $(document).ready(function(){       $(document).on('change','#photo',function(){         var property = document.getElementById('photo').files[0];         var image_name = property.name;         var image_extension = image_name.split('.').pop().toLowerCase();          if(jQuery.inArray(image_extension,['gif','jpg','jpeg','']) == -1){           alert("Invalid image file");         }          var form_data = new FormData();         form_data.append("file",property);         $.ajax({           url:'upload.php',           method:'POST',           data:form_data,           contentType:false,           cache:false,           processData:false,           beforeSend:function(){             $('#msg').html('Loading......');           },           success:function(data){             console.log(data);             $('#msg').html(data);           }         });       });     });   </script> </body>  **2.upload.php** <?php if($_FILES['file']['name'] != ''){     $test = explode('.', $_FILES['file']['name']);     $extension = end($test);         $name = rand(100,999).'.'.$extension;      $location = 'uploads/'.$name;     move_uploaded_file($_FILES['file']['tmp_name'], $location);      echo '<img src="'.$location.'" height="100" width="100" />'; } 
like image 40
Hasib Kamal Chowdhury Avatar answered Sep 19 '22 06:09

Hasib Kamal Chowdhury


You need a script that runs on the server to move the file to the uploads directory. The jQuery ajax method (running on the client in the browser) sends the form data to the server, then a script running on the server handles the upload.

Your HTML is fine, but update your JS jQuery script to look like this:

(Look for comments after // <-- )

$('#upload').on('click', function() {     var file_data = $('#sortpicture').prop('files')[0];        var form_data = new FormData();                       form_data.append('file', file_data);     alert(form_data);                                  $.ajax({         url: 'upload.php', // <-- point to server-side PHP script          dataType: 'text',  // <-- what to expect back from the PHP script, if anything         cache: false,         contentType: false,         processData: false,         data: form_data,                                  type: 'post',         success: function(php_script_response){             alert(php_script_response); // <-- display response from the PHP script, if any         }      }); }); 

And now for the server-side script, using PHP in this case.

upload.php: a PHP script that is located and runs on the server, and directs the file to the uploads directory:

<?php      if ( 0 < $_FILES['file']['error'] ) {         echo 'Error: ' . $_FILES['file']['error'] . '<br>';     }     else {         move_uploaded_file($_FILES['file']['tmp_name'], 'uploads/' . $_FILES['file']['name']);     }  ?> 

Also, a couple things about the destination directory:

  1. Make sure you have the correct server path, i.e., starting at the PHP script location what is the path to the uploads directory, and
  2. Make sure it's writeable.

And a little bit about the PHP function move_uploaded_file, used in the upload.php script:

move_uploaded_file(      // this is where the file is temporarily stored on the server when uploaded     // do not change this     $_FILES['file']['tmp_name'],      // this is where you want to put the file and what you want to name it     // in this case we are putting in a directory called "uploads"     // and giving it the original filename     'uploads/' . $_FILES['file']['name'] ); 

$_FILES['file']['name'] is the name of the file as it is uploaded. You don't have to use that. You can give the file any name (server filesystem compatible) you want:

move_uploaded_file(     $_FILES['file']['tmp_name'],     'uploads/my_new_filename.whatever' ); 

And finally, be aware of your PHP upload_max_filesize AND post_max_size configuration values, and be sure your test files do not exceed either. Here's some help how you check PHP configuration and how you set max filesize and post settings.

like image 69
bloodyKnuckles Avatar answered Sep 20 '22 06:09

bloodyKnuckles