Mustafa-Online

How To Hook File Upload Destination?

Recommended Posts

You can Hook into InputfieldFile::processInputFile. There are other places in that Class you could also hook into, but I think processInputFile works best.

Throw the code below in ready.php

Please note:

  1. Starter code: not much validation going on other than checking if the field the file was uploaded to is 'course_file'
  2. You will have to implement other logic yourself. For instance, the code copies the file immediately it is uploaded by ProcessWire Ajax. It doesn't check if the page is actually saved. If a page is not saved and the page is reloaded, as you know, files in file fields are deleted from disk. This code does not delete the corresponding file in your custom directory
  3. You might want the Hook to only run if you are in admin. You can add that logic
  4. I've purposefully left in verbose and debugging code in there (Tracy stuff) to help you ( maybe and others) understand what's going on. I suggest you test using Tracy Debugger for a better grasp of the file upload process. Delete the debugging stuff when you've got this working as you want :-).
wire()->addHookAfter("InputfieldFile::processInputFile", function(HookEvent $event)  {
    // @note: here, events are $input, $pagefile, $n @see: the method
    // get event we are hooking into
    
    // get arguments by index {a bit faster, but less-readable}
    /* $input = $event->arguments[0];
    $pagefile = $event->arguments[1];
    $n = $event->arguments[2]; */
    // get arguments by name
    #$input = $event->argumentsByName('input');
    $pagefile = $event->argumentsByName('pagefile');
    #$n = $event->argumentsByName('n');
    
    // $pagefile->field: The Field object that this file is part of.
    // limit to a specific field {course_file}
    if($pagefile->field->name != 'course_files') return;

    # intercept file
    
    // Tracy Debugger calls to see what's going on. Also logs Ajax inputs!
    #bd($input, 'input');
    #bd($n, 'input');
    // @see: http://processwire.com/api/ref/pagefile/
    // pagefile object
    bd($pagefile, 'pagefile');
    // name of the field uploading to {your 'course_file'}
    bd($pagefile->field->name, 'field pagefile is part of');
    // file-sanitized name of the file we've added, e.g. 'checklist_install.pdf'
    bd($pagefile->basename, 'name of added file');
    // full disk path where the file has been uploaded in this page's files folder...
    //... in /site/assets/files/1234 where 1234 is this page's ID
    // ... e.g. "F:/www/mysite/site/assets/files/1234/checklist_install.pdf"
    bd($pagefile->filename, 'full disk path name of added file');
    // $pagefile->page: The Page object that this file is part of
    bd($pagefile->page->id, 'id of the page file added to');

    // full disk path to your custom uploads directory
    $customDirectory = $this->wire('config')->paths->assets . 'custom_directory/';
    bd($customDirectory,'custom directory for files');
    
    # copy file
    // use ProcessWire's $files API
    // @see: http://processwire.com/api/ref/files/
    $files = $this->wire('files');
    // copy the file(s)
    $files->copy($pagefile->filename,$customDirectory . $pagefile->basename);
});

 

Edited by kongondo
  • Like 4

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

  • Recently Browsing   0 members

    No registered users viewing this page.

  • Similar Content

    • By louisstephens
      So I have been diving into hooks lately, and I am enjoying them thus far. However, I guess I am a bit stumped on how to achieve what I want too. I am trying to set up a hook that would create a new child page when the parent page is saved. However, when you save the parent page a second time, I just need to update the child page without creating multiple child pages. What would be the best way to go about this?
      So after rereading my post, I believe it is a bit vague so I will try to explain more. 
      The Goal:
      Create a page with a template "one". Once the page is created/saved => create a new child page with the template of "two" If the parent is saved anytime after, do nothing to the child page (limit the parent page to one child page) The parent page is really just being used to output content, whereas the child page is being used to pull out the some fields from the parent to be used elsewhere. I might have made this too complicated in my head.
    • By Marcel
      Hey,
      I am about to use the tool Create Users Batcher. We have 450 users. When I tryed it with like 20 test users it worked but it took a while. Now my concerns are that 450 might be to stressful? Does anyone have experience with several hundreds of users? My thoughts are to split it in smaller goups and upload them one group after another.
      best wishes
      marcel
    • By Sergio
      Hi everyone,
      Yesterday I began working on a module to create a filesystem abstraction for files and images using the Flysytem library (http://flysystem.thephpleague.com), out of the necessity of having the images copied (and probably linked) on Amazon S3 and other places like Dropbox. There two reasons why I decided to tackle this:
      1 - When I work on the project in my machine, I need a way to automatically sync the images from the server and/or the external storage.
      When an image is added on the server and the database is imported on my local env, PW shows a blank thumbnail of it. The idea for the module if to check if the page image has a width == 0 and if it exists on the server, add it to the local filesystem.
      2 - In the past, I had to move a large website to a different server in a hurry and a lot of images were left behind (it was a mess). So I'm planning for a possible future worst-case scenario of the server exploding 🙂 
      The code I quickly wrote is below (please bear with me that it's pretty raw at the moment). One thing I had to figure it out is why PW fires the Pageimage::size hook wherever a page is loaded in the admin, even though the thumbnails are already created. I was planning to save the image variations on S3 as well. Can someone clarify?
      I know that @LostKobrakai was working on a similar project, and so I would like to ask him and everyone else if you think I (and who may help) should evolve this idea into a full-featured module where the user can select which server (adapter) to use (AWS, Digital Ocean spaces, Dropbox etc.)
      <?php namespace ProcessWire; use Aws\S3\S3Client; use League\Flysystem\AwsS3v3\AwsS3Adapter; use League\Flysystem\Filesystem; use League\Flysystem\Adapter\Local; use Spatie\Dropbox\Client; use Spatie\FlysystemDropbox\DropboxAdapter; class ProcessFly extends WireData implements Module, ConfigurableModule { public static function getModuleInfo() { return array( 'title' => 'ProcessWire Flysystem Integration', 'version' => 001, 'summary' => 'Synchronize all the page assets uploaded through PW to a specified bucket in Amazon S3 and...', 'author' => 'Sérgio Jardim', 'singular' => true, 'autoload' => true, 'icon' => 'image' ); } public function init() { $this->client = S3Client::factory([ 'credentials' => [ 'key' => '', 'secret' => '', ], 'region' => 'sa-east-1', 'version' => 'latest', ]); $this->bucket_name = ""; $this->dir_name = "images"; $this->s3_adapter = new AwsS3Adapter($this->client, $this->bucket_name, $this->dir_name); $this->s3_filesystem = new Filesystem($this->s3_adapter); // DROPBOX $this->authorizationToken = ""; $this->dropbox_client = new Client($this->authorizationToken); $this->adapter_dropbox = new DropboxAdapter($this->dropbox_client); $this->dropbox_filesystem = new Filesystem($this->adapter_dropbox); $this->addHookAfter('Pages::saved', $this, 'checkImageS3'); // Download images that are not in local filesystem for whatever reason but are available in the remove one. $this->addHookAfter('InputfieldFile::fileAdded', $this, 'uploadImageS3'); // Fired when a file/image is added to a page in the admin // $this->addHookAfter('Pageimage::size', $this, 'uploadImageS3'); // Fired when a file is resized via API. Note: this hook is also called when the page is loaded in Admin. Need to know why. $this->addHookAfter('Pageimage::url', $this, 'redirectImageURL'); //Replace image URL for the S3 path } public function redirectImageURL($event){ if($event->page->template == 'admin') return; else $event->return = "https://s3-sa-east-1.amazonaws.com/[bucket name]/images/" . $event->object->page . "/" . $event->object->name; } // UPLOAD public function uploadImageS3($event){ if(count($event->return)) { //if it is a image resize event get image variation data $file = $event->return; } else { $file = $event->arguments(0); } $filename = $file->name; $filename_original = $file->url; $pathToFile = $file->page . "/" . $filename; $system_path = $file->filename(); try{ $file_on_s3 = $this->s3_filesystem->has($pathToFile); //check if file exists on AWS if(!$file_on_s3) { $contents = file_get_contents($system_path); $this->s3_filesystem->put($pathToFile, $contents, array( 'visibility' => 'public', )); //upload file with the same folder structure as in assets/files: page_id/file_name //Also add a copy to Dropbox (OPTIONAL) $this->dropbox_filesystem->put($pathToFile, $contents); } } catch (Exception $e){ throw new WireException("Error: Image not Added to S3: {$e->getMessage()}"); } } public function checkImageS3($event){ $page = $event->arguments(0); if(count($page->images)) { foreach($page->images as $file) { if($file->width == 0) { return $this->downloadImageS3($page, $file); }; } } } public function downloadImageS3($page, $file){ $pathToFile = $page->id . "/" . $file->name; $file_on_s3 = $this->s3_filesystem->has($pathToFile); //check if file exists on AWS if($file_on_s3) { $image = "https://s3-sa-east-1.amazonaws.com/[bucket name]/images/" . $pathToFile; // $page->images->remove($image); $page->images->add($image); $page->save(); } else { throw new WireException("Error: Image not found on S3: {$file->name}"); } } }  
    • By quickjeff
      Hi Guys,
      I am running a page template that contains a filter form that allows users to display results based on number of  comments. 
      Here is what I am thinking about doing: 
      -add new field called total_comments 
      -somehow populate this field every time a new comment is added or removed by admin with count($page->comments)
      -use form filter to display results that the selector form has found.
      Example: $selector = “total_comments>=$q”; 
       
      My question to everyone: Is this a good approach? If so how do I get another field to update based on the comment module adding or removing a comment? 
    • By rgaikema
      Hi all,
      Hopefully there's somebody who can help me with an issue while unzipping files.
      My goal is to show banners in a portfolio.
      In ProcessWire I have created a field, type 'Files', where I can upload the .zip files, one at a time.
      I've selected the option Decompress ZIP files, but any subfolder in the .zip somehow disappears.
      For example the 'assets' folder is gone after I uploaded the .zip file (see the attachment for the file structure).
      I'm curious, is there a way to preserve the file structure inside a .zip file after unzipping it?
       
      Kind regards,
      Remco