CakePHP 1.3 and Uploadifive/Uploadify - Change Upload Filename to a random string

Posted by CaboONE on Stack Overflow See other posts from Stack Overflow or by CaboONE
Published on 2012-06-05T04:31:09Z Indexed on 2012/06/05 4:40 UTC
Read the original article Hit count: 460

Filed under:
|

I have somehow implemented UPLOADIFIVE in my CakePHP application. Everything seems to work great including uploading multiple files and inserting the correct information in the Database.

Based on the following code, I would like to UPLOAD AND SAVE EVERY FILE WITH A RANDOM NAME TAKING INTO ACCOUNT THE CURRENT DATE OR SOMETHING SIMILAR.

How could I accomplish this?

In my Photos Controller I have the following function:

// This function is called at every file upload. It uploads the file onto the server
// and save the corresponding image name, etc, to the database table `photos`.
function upload() {
    $uploadDir = '/img/uploads/photos/';

    if (!empty($_FILES)) {
        debug($_FILES);

        $tempFile   = $_FILES['Filedata']['tmp_name'][0];
        $uploadDir  = $_SERVER['DOCUMENT_ROOT'] . $uploadDir;
        $targetFile = $uploadDir . $_FILES['Filedata']['name'][0];

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

        // Validate the filetype
        if (in_array($fileParts['extension'], $fileTypes)) {

            // Save the file
            move_uploaded_file($tempFile,$targetFile);

            $_POST['image'] = $_FILES['Filedata']['name'][0];           

            $this->Photo->create();
            if ($this->Photo->save($_POST)) {
                $this->Session->setFlash($targetFile, 'default', array('class' => 'alert_success'));
                $this->redirect(array('action' => 'index'));
            }
        } else {
            // The file type wasn't allowed
            //echo 'Invalid file type.';
            $this->Session->setFlash(__('The photo could not be saved. Please, try again.', true));
        }
    }
}

In my View file - admin_add.ctp I have added the following function

$('#file_upload').uploadifive({
    'auto' : false,
    'uploadScript' : '/photos/upload',
    'buttonText' : 'BROWSE FILES',
    'method'   : 'post',
    'onAddQueueItem' : function(file) {
        this.data('uploadifive').settings.formData = { 'photocategory_id' : $('#PhotoPhotocategoryId').val() };
    }
}); 


<input type="file" name="file_upload" id="file_upload" />

© Stack Overflow or respective owner

Related posts about cakephp

Related posts about cakephp-1.3