jQuery File Upload Plugin: How to upload to subfolders?

jquery, jquery-plugins

Solution

Firt, the obvious should be stated: you can't actually set the upload destination with JavaScript/jQuery/jWhateverPlugin (i.e. from the client-side), for obvious security reasons.

But you can pass information along to the server-side engine (in your case, PHP), which may use it to manage the actual storage of the upload.

Various toolkits exist to help you with, like blueimp's jQuery File Upload you initially started with, or Uploadify, that Benno first promoted and seemed to meet your requirements.

So what you have to do is customize both client-size and server-side scripts to implement passing along the directory variable(s) and using them to define storage location.

Heavily based on the Uploadify documentation, and using your `project_uid` variable, this whould look like this:

On the client-side (JavaScript + jQuery + Uploadify):

var project_uid;
// populate project_uid according to your needs and implementation
// befor using uploadify

$('#file_upload').uploadify({
    'method'   : 'post',

    // pass your variable to the server
    'formData' : { 'project_uid' : project_uid },

    // optional "on success" callback
    'onUploadSuccess' : function(file, data, response) { 
        alert('The file was saved to: ' + data);
    }
});

And on the server-side (PHP + Uploadify):

// Set $someVar to 'someValue'
$untrustedProjectUid = $_POST['project_uid'];

// Remember to check heavily the untrusted received variable.
// Let's pretend you checked it, it passe your tests, so you
// initialized a trusted var with it
$trustedProjectUid = ensureSecure( $untrustedProjectUid );

$targetFolder = '/uploads/' . $trustedProjectUid . '/' ; // Relative to the root


if (!empty($_FILES)) {
    $tempFile = $_FILES['Filedata']['tmp_name'];
    $targetPath = $_SERVER['DOCUMENT_ROOT'] . $targetFolder;
    $targetFile = rtrim($targetPath,'/') . '/' . $_FILES['Filedata']['name'];

    // Validate the file type
    $fileTypes = array('jpg','jpeg','gif','png'); // Put you allowed file extensions here
    $fileParts = pathinfo($_FILES['Filedata']['name']);

    if (in_array($fileParts['extension'],$fileTypes)) {
        move_uploaded_file($tempFile,$targetFile);
        echo $targetFolder . '/' . $_FILES['Filedata']['name'];
    } else {
        echo 'Invalid file type.';
    }
} 

Problem

I have the jQuery File Upload plugin working on a PHP site. I was wondering if it's possible to have the files uploaded into a dynamically-named subfolder rather than all going into the same uploads folder? Reason being is I need a separate folder for files uploaded in each 'project' being created by the user on the site. E.g. when a user creates a project, everything they upload for that project with go into /uploads/{$project_uid}/{$file_name} I hope I've explained myself properly and would really appreciate it if anyone could help me out here. Thanks!

Original source