Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

"Blueimp jQuery File Upload" rename files

Tags:

jquery

php

I'm using the Blueimp jQuery file upload tool. I'd like to completely rename the files as they're uploaded. Since photos are being added to a unique directory based on the userID, I'd really just like to add photos with names 001.jpg, 002.jpg, 003.jpg, etc. How can I accomplish this (either by modifying UploadHandler.php or index.php?

In index.php (code below currently changes the upload directory):

$userID = 'user005'; //hardcoded in this example
$options = array('upload_dir'=>'files/'.$userID.'/', 'upload_url'=>'files/'.$userID.'/');
$upload_handler = new UploadHandler($options);
like image 391
user2755541 Avatar asked Mar 12 '14 16:03

user2755541


2 Answers

Old post, but as I was searching the same thing today, I post my solution hoping it will help someone.

I edited the UploadHandler.php file in this way:

        //custom function which generates a unique filename based on current time
        protected function generate_unique_filename($filename = "")
            {

                $extension = "";
                if ( $filename != "" )
                {
                    $extension = pathinfo($filename , PATHINFO_EXTENSION);

                    if ( $extension != "" )
                    {
                        $extension = "." . $extension;
                    }
                }

                return md5(date('Y-m-d H:i:s:u')) . $extension;
            }


            protected function handle_file_upload($uploaded_file, $name, $size, $type, $error,
                    $index = null, $content_range = null) {
                $file = new \stdClass();

                //MYEDIT to generate unique filename
                $file->name = $this->generate_unique_filename($name);

                //ORIGINAL LINE: $file->name = $this->get_file_name($uploaded_file, $name, $size, $type, $error, $index, $content_range);

                //...
}
like image 113
SaganTheBest Avatar answered Oct 09 '22 08:10

SaganTheBest


For those who only what to give the name through the $options:

Replace (line 1056?)

$file->name = $this->get_file_name($uploaded_file, $name, $size, $type, $error, $index, $content_range);

with

$extension = pathinfo($name , PATHINFO_EXTENSION);
if ( $extension != "" ){
    $extension = "." . $extension;
}

$file->name = (isset($this->options['filename']) && isset($extension) ) 
     ? $this->options['filename'] . $extension
     : $this->get_file_name($uploaded_file, $name, $size, $type, $error, $index, $content_range);

Then give the name in the option like this:

$upload_handler = new UploadHandler(array(['filename' => 'whatever' ]));
like image 28
Matt Avatar answered Oct 09 '22 09:10

Matt