1

I have been trying to upload a file from my webpage to a folder on the server using jQuery and PHP.

Here is my JavaScript code for generating the file to send and then using a POST request to send the file to my PHP script so that it can then handle the file and save it to a particular folder.

//Generate file to send to server
var formData = new FormData();
var characterBlob = new Blob([result], {type: "octet/stream"});
formData.append('Character', characterBlob);

//Communicate with the server
$.ajax({
    url: "ExecuteMaya.php", // Url to which the request is send
    type: "POST",             // Type of request to be send, called as method
    data: formData, // Data sent to server, a set of key/value pairs (i.e. form fields and values)
    contentType: false,       // The content type used when sending data to the server.
    cache: false,             // To unable request pages to be cached
    processData:false,        // To send DOMDocument or non processed data file it is set to false
    success: function(data)   // A function to be called if request succeeds
{
    $('#loading').hide();
    $("#message").html(data);
}
});

Here is my PHP script to handle the sent file and save it in a specified folder.

<?php
$sourcePath = $_FILES['file']['tmp_name'];       // Storing source path of the file in a variable
$targetPath = "/Applications/AMPPS/www/webGL/upload/".$_FILES['file']['name']; // Target path where file is to be stored
move_uploaded_file($sourcePath,$targetPath) ;    // Moving Uploaded file
echo "<span id='success'>Image Uploaded Successfully...!!</span><br/>";
echo "<br/><b>File Name:</b> " . $_FILES["file"]["name"] . "<br>";
echo "<b>Type:</b> " . $_FILES["file"]["type"] . "<br>";
echo "<b>Size:</b> " . ($_FILES["file"]["size"] / 1024) . " kB<br>";
echo "<b>Temp file:</b> " . $_FILES["file"]["tmp_name"] . "<br>";
?>

When I try to send the file from my webpage nothing appears in the 'Upload' folder that I am trying to save the file to.

Could someone please tell me why a file is not saved in the 'Upload' folder? I am eventually looking to open this file in a Maya application on the server and run some Python code. Would I even need to save the file on the server before opening it in Maya? Or could I open Maya with the file straight away?

skelto
  • 157
  • 1
  • 11
  • Do you have errors in your console?! Is your target path correct? Please use console.log(data) in your AJAX success function and see what you get. – Ionut Necula Jun 15 '16 at 13:51
  • if no error and if your file path is also correct, then please check the permisson of upload folder – aniket ashtekar Jun 15 '16 at 13:54
  • @Ionut there are no errors in the console. I've tried the full path "/Applications/AMPPS/www/webGL/upload/" and just "upload/" as the path with no luck. "/Applications/AMPPS/www/webGL/upload/" is the correct full path to the folder that I want to save the file in. – skelto Jun 15 '16 at 13:55
  • @aniketashtekar would I check this permission in the php.ini file? – skelto Jun 15 '16 at 13:55
  • Do you get those "echos" in the console? And @aniketashtekar, refers to the permissions of the upload folder. – Ionut Necula Jun 15 '16 at 13:57
  • @Ionut there are no echos in the console. – skelto Jun 15 '16 at 13:58
  • @aniketashtekar how would I change the permission of the upload folder? – skelto Jun 15 '16 at 14:00
  • @skelto, maybe the path of the php file from AJAX is not correct. All the files are located in the same directory? – Ionut Necula Jun 15 '16 at 14:04
  • @Ionut Yes all the files are located in the same directory. I tried changing the path of the PHP file from AJAX to the full path, which threw up a 404 (Not Found) error. – skelto Jun 15 '16 at 14:11
  • If you have a 404 error after you changed the path in AJAX to full path then the problem lies in the permissions. Are you using somekind of FTP client? If yes, go to the folder where you're trying to upload the files and right click on that, and there should be a button called "File permissions", or something like that. See if all the cases are checked. Also, check my answer bellow. – Ionut Necula Jun 15 '16 at 14:13

2 Answers2

0

It seems you are not appending the file to uploaded to the form data, May be you need something like this.

var elem = $(this).val() // lets say this is the element where you uploaded the photo
var formData = new FormData();
formData.append('file', elem[0].files[0]);
$.ajax({
    url: "ExecuteMaya.php",
    type: "POST",
    data : formData,
    processData: false,  // tell jQuery not to process the data
    contentType: false,
    success: function(result){
 // your code executed successfully
}
0

Try use my code and tell me if it works. This should work if you adapt it to your filenames and input, and other elements ids, it's tested by me:

$('#upload').on('click', function(e) {
  $('#message').fadeOut();
  e.preventDefault();
  if ($('#file')[0].files.length == 0) {
    alert('Choose a file!');
  } else {
    var file_data = $('#file').prop('files')[0]; //file object details  
    var form_data = new FormData($('#form')[0]);
    form_data.append('file', file_data);
    var unique_identifier = $('#unique_identifier').val();
    $.ajax({
      url: 'upload.php',
      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) {
        $('#message').html(php_script_response).fadeIn();
        //alert(php_script_response); // display response from the PHP script, if any
      }
    });
  }
});
<form id='form' action='' method='post' enctype='multipart/form-data'>
  <input type='hidden' name='unique_identifier' id='unique_identifier' placeholder='unique identfier' value="<?php echo rand(1000000, 9999999); ?>">
  <input type='file' name='file' id='file' />
  <a id='upload'>Upload</a>
</form>

And the PHP script I made:

$unique_identifier = (isset($_POST['unique_identifier']))?trim($_POST['unique_identifier']):'';
$upload_directory = 'upload/' . $unique_identifier . '/';
if (!file_exists($upload_directory)) {
    mkdir ($upload_directory, 0777);
}
$original_filename = basename($_FILES['file']['name']);
$destination = $upload_directory . $original_filename;

move_uploaded_file($_FILES['file']['tmp_name'], $destination)

Also, I recomend you to do some PHP validation.

Ionut Necula
  • 11,107
  • 4
  • 45
  • 69
  • For this line - var file_data = $('#file').prop('files')[0]; I set it equal to a Blob file that I generate. Is this viable? I will need to send a Blob file to the server. – skelto Jun 15 '16 at 14:22
  • No, you don't need to do that. Use my code. It should work. – Ionut Necula Jun 15 '16 at 14:23
  • An empty folder with the name '' is now being saved to my 'Upload' folder. What do I need to replace in the JavaScript code so that the desired file is sent to the server? – skelto Jun 15 '16 at 14:31
  • Put the AJAX code I gave you in the same file as the form between script tags. – Ionut Necula Jun 15 '16 at 15:06
  • I have now put the code where you have stated. I get the following error when running the code - 'Uncaught TypeError: Cannot read property '0' of undefined'. Are you sure that I don't need to change the variable 'file_data' to equal the Blob file that I want to send? Thanks for all the help. – skelto Jun 15 '16 at 16:01
  • @lonut You don't need to append file to the form data. It is already part of form data when you do `new FormData($('#form')[0])` – Mikey Jun 15 '16 at 18:19
  • @Mikey I've been able to send a Blob file to the server and save it in the folder. I did so by creating this simple Blob - var blob = new Blob(['foo', 'bar']); I want to be able to send a file of type .OBJ (a file type used in Maya to define a geometry). Would you know how I could send this more complex type of Blob? I create my .OBJ Blob using this line - var characterBlob = new Blob([result], {type: "octet/stream"}); – skelto Jun 16 '16 at 13:41
  • @skelto Are you using an input `file` field to upload this `.obj` file? If so, then there's no reason to use `Blob`. And how big is this `.obj` file? Although this answer is over-complicating things, it should work. When you open your browser's developer tool, what does it say under the Network (XHR) tab? Is there any errors? – Mikey Jun 16 '16 at 14:43
  • @Mikey the .OBJ file is 3MB. I'm not using an input file field. I am making an online avatar creator, so the .OBJ that needs to be sent is a character model that has been loaded into the Three.js scene. There are no errors under the XHR tab. – skelto Jun 16 '16 at 14:48
  • @Mikey really stuck on this one, would you be able to help? I made a new question to more clearly state my problem - http://stackoverflow.com/questions/37878318/how-do-i-send-a-blob-of-type-octet-stream-to-server-using-ajax – skelto Jun 20 '16 at 10:13