Please upgrade here. These earlier versions are no longer being updated and have security issues.
HackerOne users: Testing against this community violates our program's Terms of Service and will result in your bounty being denied.

How can I keep the orginal name of the uploaded image?

When uploading an image , for example IMAGE.jpg, the name is changed in something like X2K10WYTCQBC.jpg

Is it possible to keep the original name ofthe file? If yes, how can I do that? I am using ImageUpload plugin, version **1.0.1 **

Thank you.

«1

Comments

  • peregrineperegrine MVP
    edited August 2014

    Since the savedimages names are put in random number folders to avoid collision (and overwrites if someone uploads an image with the same name that happens to be in the same random number folder).

    but if you want to take a chance -

    you could modify the image upload plugin to this.

                       // Generate the target image name.
                        // $TargetImage = $UploadImage->GenerateTargetName(PATH_UPLOADS.'/imageupload', '', TRUE);
                                    $TargetFolder = PATH_UPLOADS.'/imageupload';
                                    $Name =$UploadImage->GetUploadedFileName();
                                    $Subdir = sprintf('%03d', mt_rand(0, 999)).'/';
    
                                    $TargetImage = "$TargetFolder/{$Subdir}$Name";
    

    I may not provide the completed solution you might desire, but I do try to provide honest suggestions to help you solve your issue.

  • Where should I add these code lines?

  • peregrineperegrine MVP
    edited August 2014

    you modify the plugin! class.imageupload.plugin.php

    but be forewarned - if people upload images with the same name they could be replaced (since they are not unique names.)

    the other option is to add a random number to the front of the image name to reduce collision possibility, which would be better.

        // Generate the target image name.
                    // $TargetImage = $UploadImage->GenerateTargetName(PATH_UPLOADS.'/imageupload', '', TRUE);
                                $TargetFolder = PATH_UPLOADS.'/imageupload';
                                 $Name = $UploadImage->GetUploadedFileName();
                                $Subdir = sprintf('%03d', mt_rand(0, 999)).'/';
                                $Prefix =  mt_rand(0, 999) . "-";
                                $TargetImage = "$TargetFolder/{$Subdir}{$Prefix}$Name";
    

    I may not provide the completed solution you might desire, but I do try to provide honest suggestions to help you solve your issue.

  • Thanks. I'll try it.

  • It works.

    After adding your code, the uploaded image keeps it's original name except the fact that a random number is added in the front of the image name. This way, the new added images will not overwrite any image on the server.

    Thank you, peregrine.

  • I put a random number (from 0-999) Prefix. in front of image name - to "help avoid" overwriting, which is not as foolproof as the 12 character random string that was previously used to replace the name.

    but if it works for you great.

    I may not provide the completed solution you might desire, but I do try to provide honest suggestions to help you solve your issue.

  • The reason why I wanted to keep the file's name is the search engine. I believe the search engines can easily find and index an image when the image have a it's original name. I may be wrong, I don't know, but for me it's ok this way and I thank you for your great help.

  • KristianBKristianB
    edited March 2015

    I have recently shifted from Vanilla 1 to Vanilla 2.1.8 and use the ImageUplod plugin - with the above modification as to keeping the original file name - with great pleasure. Thanks a lot! I should, however, like to have the images uploadet to a folder for each individual user and not in random number folders. I believe that the UserID has to replace the random number somewhere in the these lines:

     $Subdir = sprintf('%03d', mt_rand(0, 999)).'/';
     $TargetImage = "$TargetFolder/{$Subdir}$Name";
    

    but as I am not familiar with php I should like to ask if someone would be so kind to help with the proper expression.

  • @KristianB your best bet would be to extend the Gdn_UploadImage class (which is what this plugin uses) and override the GenerateTargetName() method:

    class KristianB_UploadImage extends Gdn_UploadImage {
     public function GenerateTargetName($TargetFolder, $Extension = 'jpg', $Chunk = FALSE) {
       if (!$Extension) {
          $Extension = trim(pathinfo($this->_UploadedFile['name'], PATHINFO_EXTENSION), '.');
       }
    
       // Get the currently signed in user
       $UserID = Gdn::Session()->UserID;
       do {
          $Name = RandomString(12);
          $Subdir = $UserID . '/';
          $Path = "$TargetFolder/{$Subdir}$Name.$Extension";
       } while(file_exists($Path));
       return $Path;
     }
    }
    

    Then fork this ImageUpload plugin to use your new class (line 4 below is the only change):

    public function PostController_Imageupload_create()
    {
      try {
        $UploadImage = new KristianB_UploadImage();
        $TmpImage = $UploadImage->ValidateUpload('image_file');
        // Generate the target image name.
        $TargetImage = $UploadImage->GenerateTargetName(PATH_UPLOADS.'/imageupload', '', TRUE);
        $Props = $UploadImage->SaveImageAs($TmpImage,$TargetImage,C('Plugins.UploadImage.MaxHeight',''),C('Plugins.UploadImage.MaxWidth',650));
        echo json_encode(array('url'=>$Props['Url'],'name'=>$UploadImage->GetUploadedFileName()));
      } catch (Exception $e) {
        header('HTTP/1.0 400', TRUE, 400);
        echo $e;
      }
    }
    

    Search first

    Check out the Documentation! We are always looking for new content and pull requests.

    Click on insightful, awesome, and funny reactions to thank community volunteers for their valuable posts.

  • Thank you for your advice. I will try to locate where to insert new code and where to replace/change existing program lines. I will post a reply when I have had time to see if I can make it work.

  • KristianBKristianB
    edited March 2015

    It is quite embarrassing but I am simply too stupid to make it right. The entire code for class.imageupload.plugin.php - after making the above changes to keep the original image file name - is:

    <?php if (!defined('APPLICATION')) exit();
    
    $PluginInfo['ImageUpload'] = array(
        'Name' => 'ImageUpload',
        'Description' => 'lightweight and simple image uploader',
        'Version' => '1.1.1',
        'RequiredApplications' => array('Vanilla' => '2.0.18.4'),
        'RequiredTheme' => FALSE,
        'RequiredPlugins' => FALSE,
        'MobileFriendly' => TRUE,
        // 'HasLocale' => TRUE,
        'RegisterPermissions' => FALSE,
        'Author' => "chuck911",
        'AuthorEmail' => 'contact@with.cat',
        'AuthorUrl' => 'http://vanillaforums.cn/profile/chuck911'
    );
    
    class ImageUploadPlugin extends Gdn_Plugin {
    
        public function DiscussionController_BeforeBodyField_Handler($Sender)
        {
            echo $Sender->FetchView($this->GetView('upload_button.php'));
        }
    
        public function PostController_BeforeBodyInput_Handler($Sender)
        {
            echo $Sender->FetchView($this->GetView('upload_button.php'));
        }
    
        public function Base_Render_Before($Sender) {
            if(!in_array(get_class($Sender), array('PostController','DiscussionController')))
                return;
            $Sender->AddDefinition('ImageUpload_Url',Url('/post/imageupload'));
            $Sender->AddDefinition('ImageUpload_Multi',C('Plugins.UploadImage.Multi',TRUE));
            $Sender->AddDefinition('ImageUpload_InputFormatter',C('Garden.InputFormatter', 'Html'));
            $Sender->AddDefinition('ImageUpload_MaxFileSize', C('Plugins.UploadImage.MaxFileSize', '2mb'));
            $Sender->AddCssFile('imageupload.css', 'plugins/ImageUpload/css');
            $Sender->AddJsFile('plupload.full.js', 'plugins/ImageUpload');
            $Sender->AddJsFile('imageupload.js', 'plugins/ImageUpload');
        }
    
        public function PostController_Imageupload_create()
        {
            try {
                $UploadImage = new Gdn_UploadImage();
                $TmpImage = $UploadImage->ValidateUpload('image_file');
    
                // Generate the target image name. 
                // $TargetImage = $UploadImage->GenerateTargetName(PATH_UPLOADS.'/imageupload', '', TRUE);
                                    $TargetFolder = PATH_UPLOADS.'/imageupload';
                                    $Name =$UploadImage->GetUploadedFileName();
                                    $Subdir = sprintf('%03d', mt_rand(0, 999)).'/';
                                    $TargetImage = "$TargetFolder/{$Subdir}$Name";
    
                $Props = $UploadImage->SaveImageAs($TmpImage,$TargetImage,C('Plugins.UploadImage.MaxHeight',''),C('Plugins.UploadImage.MaxWidth',650));
                echo json_encode(array('url'=>$Props['Url'],'name'=>$UploadImage->GetUploadedFileName()));
            } catch (Exception $e) {
                header('HTTP/1.0 400', TRUE, 400);
                echo $e;
            }
        }
    }
    

    I have tried to make the changes that you have suggested but I either get 1) a total blank forum or 2) an error message when trying to edit a comment. I would be very grateful if you would point out exactly where to insert or substitute the code that you have given above.

  • hgtonighthgtonight MVP
    edited March 2015

    Sample of untested code:

    <?php if (!defined('APPLICATION')) exit();
    $PluginInfo['ImageUpload'] = array(
    'Name' => 'ImageUpload',
    'Description' => 'lightweight and simple image uploader',
    'Version' => '1.1.1',
    'RequiredApplications' => array('Vanilla' => '2.0.18.4'),
    'RequiredTheme' => FALSE,
    'RequiredPlugins' => FALSE,
    'MobileFriendly' => TRUE,
    // 'HasLocale' => TRUE,
    'RegisterPermissions' => FALSE,
    'Author' => "chuck911",
    'AuthorEmail' => 'contact@with.cat',
    'AuthorUrl' => 'http://vanillaforums.cn/profile/chuck911'
    );
    
    class KristianB_UploadImage extends Gdn_UploadImage {
      public function GenerateTargetName($TargetFolder, $Extension = 'jpg', $Chunk = FALSE) {
        if (!$Extension) {
          $Extension = trim(pathinfo($this->_UploadedFile['name'], PATHINFO_EXTENSION), '.');
        }
        // Get the currently signed in user
        $UserID = Gdn::Session()->UserID;
        do {
          $Name = RandomString(12);
          $Subdir = $UserID . '/';
          $Path = "$TargetFolder/{$Subdir}$Name.$Extension";
        } while(file_exists($Path));
        return $Path;
      }
    }
    
    class ImageUploadPlugin extends Gdn_Plugin {
      public function DiscussionController_BeforeBodyField_Handler($Sender)
      {
        echo $Sender->FetchView($this->GetView('upload_button.php'));
      }
      public function PostController_BeforeBodyInput_Handler($Sender)
      {
        echo $Sender->FetchView($this->GetView('upload_button.php'));
      }
      public function Base_Render_Before($Sender) {
        if(!in_array(get_class($Sender), array('PostController','DiscussionController')))
          return;
        $Sender->AddDefinition('ImageUpload_Url',Url('/post/imageupload'));
        $Sender->AddDefinition('ImageUpload_Multi',C('Plugins.UploadImage.Multi',TRUE));
        $Sender->AddDefinition('ImageUpload_InputFormatter',C('Garden.InputFormatter', 'Html'));
        $Sender->AddDefinition('ImageUpload_MaxFileSize', C('Plugins.UploadImage.MaxFileSize', '2mb'));
        $Sender->AddCssFile('imageupload.css', 'plugins/ImageUpload/css');
        $Sender->AddJsFile('plupload.full.js', 'plugins/ImageUpload');
        $Sender->AddJsFile('imageupload.js', 'plugins/ImageUpload');
      }
    
      public function PostController_Imageupload_create()
      {
        try {
          $UploadImage = new KristianB_UploadImage();
          $TmpImage = $UploadImage->ValidateUpload('image_file');
          // Generate the target image name.
          $TargetImage = $UploadImage->GenerateTargetName(PATH_UPLOADS.'/imageupload', '', TRUE);
          $Props = $UploadImage->SaveImageAs($TmpImage,$TargetImage,C('Plugins.UploadImage.MaxHeight',''),C('Plugins.UploadImage.MaxWidth',650));
          echo json_encode(array('url'=>$Props['Url'],'name'=>$UploadImage->GetUploadedFileName()));
        } catch (Exception $e) {
          header('HTTP/1.0 400', TRUE, 400);
          echo $e;
        }
      }
    }
    

    This should replace the file /plugins/ImageUpload/class.imageupload.plugin.php. You could also replace the Upload Image class, but that would require you to keep it up to date with core changes for the whole file while this means you only need to keep track of a single method.

    Search first

    Check out the Documentation! We are always looking for new content and pull requests.

    Click on insightful, awesome, and funny reactions to thank community volunteers for their valuable posts.

  • Thank you for your patience. I have substituted the entire code in class.imageupload.plugin.php with the code you give but when I go to a comment and click on Edit I get the following error message:

    If uploading images to UserID specific folders is impossible, the only option I have (with my very limited programming skills) would be to place all images in a single folder, thus avoiding having 999 random number folders.

  • What is the URL of the error?

    Enable debug mode to get more information.

    Search first

    Check out the Documentation! We are always looking for new content and pull requests.

    Click on insightful, awesome, and funny reactions to thank community volunteers for their valuable posts.

  • I have enabled debug mode. It is most certainly easier for you to find the relevant and critical details so I attach at text file of what is displayed on the screen. I believe that you can delete the attachment when you have received it.

  • Is there a file in /plugins/ImageUpload/views?

    Search first

    Check out the Documentation! We are always looking for new content and pull requests.

    Click on insightful, awesome, and funny reactions to thank community volunteers for their valuable posts.

  • Yes - cf. attached screen print from my ftp program (FileZilla).

    By the way, the whoops message is shown whenever the "Leave a Comment" window should be displayed, not only after having clicked Edit but also at the bottom of a thread (just like the one in which I type this message).

  • Hmmm...

    And reverting back to the unmodified plugin gets rid of the error?

    Search first

    Check out the Documentation! We are always looking for new content and pull requests.

    Click on insightful, awesome, and funny reactions to thank community volunteers for their valuable posts.

  • KristianBKristianB
    edited March 2015

    Yes, then I can write - and edit - text and upload images in new comments. (At present I use the unmodified plugin: http://naturnettet.dk/2/traade1.htm )

    The reason why I should like to have all images in UserID specific folders is that in the old forum (Vanilla 1) I used the plugin InlineImages with this option (either a new folder every month or a permanent folder for each user). I then made a very useful gallery where all uploaded images from each user were displayed (http://naturnettet.dk/Arkiv/naturnettet.dk/arkivgalleri.htm ). I should very much like to be able to do the same in Vanilla 2.

  • P.S. *unmodified = the original plugin but modified to keep the original image file name!

Sign In or Register to comment.