We launched new forums in March 2019—join us there. In a hurry for help with your website? Get Help Now!
    • 16633
    • 116 Posts
    I was wondering if it is possible to upload a file to the /assets/ folder using formit?

    I am using the latest release of revolution.
      --
      Landon Poburan
      Web Designer and Developer

      http://www.categorycode.ca
      http://www.landonp.com
    • Since you marked this solved, could you elaborate on how you did this to help others who want the same?
        Mark Hamstra • Developer spending his days working on Premium Extras and a MODX Site Dashboard with the ability to remotely upgrade MODX and extras to make the MODX world a little better.

        Tweet me @mark_hamstra, check my infrequent blog at markhamstra.com, my slightly more frequent ramblings at MODX.today or see code at Github.
        • 16633
        • 116 Posts
        I am using formit2resource for a form that creates a resource but I also wanted to upload a file inside that form. I created a hook called formit2file which runs before the formit2resource hook so that if it fails, it does not create the resource.

        Here is the code for formit2file
        <?php
        
        $path; // Path from root that user specifies
        $extensions; // allow file extensions
        
        $ext_array = explode(',', $extensions);
        
        // Create path
        $basepath = $modx->config['base_path']; // Site root
        $target_path = $basepath . $path; // root /assets/upload
        
        //$target_path = '/home/emeraldfound/emeraldfoundation.ca/assets/uploads/';
        
        // Get Filename and make sure its good.
        $filename = basename( $_FILES['nomination_file']['name'] );
        
        // Get files extension
        $ext = pathinfo($filename, PATHINFO_EXTENSION);
        
        if($filename != '')
        {
            // Make filename a good unique filename.
            // Make lowercase
            $filename = mb_strtolower($filename);
            // Replace spaces with _
            $filename = str_replace(' ', '_', $filename);
            // Add timestamp
            $filename = date("Ymdgi") . $filename;
        
            // Set final path
            $target_path = $target_path . $filename;
        
            if(in_array($ext, $ext_array))
            {
                if(move_uploaded_file($_FILES['nomination_file']['tmp_name'], $target_path))
                {
                    // Upload successful
                    //$hook->setValue('nomination_file',$_FILES['nomination_file']['name']);
                    $hook->setValue('nomination_file',$filename);
                    return true;
                }
                else
                {
                    // File not uploaded
                    $errorMsg = 'File not uploaded.';
                    $hook->addError('nomination_file',$errorMsg);
                    return false;
                }
            }
            else
            {
                // File type not allowed
                $errorMsg = 'File not allowed.';
                $hook->addError('nomination_file',$errorMsg);
                return false;
            }
        }
        else
        {
            $hook->setValue('nomination_file','');
            return true;
        }
        
        return true;
        ?>
        


        Here is the form field I am using
        <div class="row clearfix">
                <div class="label">Supplementary Files <br /><span class="error">[[+fi.error.nomination_file]]</span></div> <!-- end of .label -->
                <div class="input"><input id="nomination_file" name="nomination_file" type="file" value="[[+fi.nomination_file]]" maxlength="100000" /></div> <!-- end of .input -->
            </div> <!-- end of .row -->
        


        In the formit snippet call I set a few values that I use in formit2file
        &path = `assets/uploads/`
            &extensions = `jpg,JPG,jpeg,JPEG,doc,docx,pdf,txt,png,zip,mov,avi,mpeg,mp4`
            &maxsize = `20971520`
        


        Here is how I call the hook
        &hooks=`spam,formit2file,formit2resource,email,FormItAutoResponder,redirect`
        
          --
          Landon Poburan
          Web Designer and Developer

          http://www.categorycode.ca
          http://www.landonp.com
        • Thanks! smiley
            Mark Hamstra • Developer spending his days working on Premium Extras and a MODX Site Dashboard with the ability to remotely upgrade MODX and extras to make the MODX world a little better.

            Tweet me @mark_hamstra, check my infrequent blog at markhamstra.com, my slightly more frequent ramblings at MODX.today or see code at Github.
            • 6902
            • 126 Posts
            I modified the hook/snippet so that it can accept multiple files and can auto-create the upload directory if it doesn’t exist.

            *Note: that if the user uploads multiple files with the same name they will overwrite each other unless you add some type of random salt to the file name (more than just a date/time stamp).
            *Note: also, don’t forget to add the requisite enctype="multipart/form-data" to your <form> tag! ... I spent an embarrassing amount of time trying to figure out what was wrong before having a "doh!" moment!

            <?php
            
            // initialize output;
            $output = true;
            
            // valid extensions
            $ext_array = array('pdf', 'txt', 'doc', 'docx', 'rtf');
            
            // create unique path for this form submission
            $uploadpath = 'assets/uploads/';
            
            // you can create some logic to automatically
            // generate some type of folder structure here.
            // the path that you specify will automatically
            // be created by the script if it doesn't already
            // exist.
            
            // EXAMPLE:
            // this would put all file uploads into a new,
            // unique folder every day.
            // $uploadpath = 'assets/'uploads/'.date('Y-m-d').'/';
            
            // get full path to unique folder
            $target_path = $modx->config['base_path'] . $uploadpath;
            
            // get uploaded file names:
            $submittedfiles = array_keys($_FILES);
            
            // loop through files
            foreach ($submittedfiles as $sf) {
            
            	// Get Filename and make sure its good.
            	$filename = basename( $_FILES[$sf]['name'] );
            
            	// Get file's extension
            	$ext = pathinfo($filename, PATHINFO_EXTENSION);
            	$ext = mb_strtolower($ext); // case insensitive
            
            	// is the file name empty (no file uploaded)
            	if($filename != '') {
                	
            		// is this the right type of file?
            		if(in_array($ext, $ext_array)) {
             	
            			// clean up file name and make unique
            			$filename = mb_strtolower($filename); // to lowercase
            			$filename = str_replace(' ', '_', $filename); // spaces to underscores
            			$filename = date("Y-m-d_G-i-s_") . $filename; // add date & time
            			
            			// full path to new file
            			$myTarget = $target_path . $filename;
            			
            			// create directory to move file into if it doesn't exist
            			mkdir($target_path, 0755, true);
            			
            			// is the file moved to the proper folder successfully?
            			if(move_uploaded_file($_FILES[$sf]['tmp_name'], $myTarget)) {
            				// set a new placeholder with the new full path (if you need it in subsequent hooks)
            				$modx->setPlaceholder('fi.'.$sf.'_new', $myTarget);
            				// set the permissions on the file
            				if (!chmod($myTarget, 0644)) { /*some debug function*/ }
            				
                    	} else {
            				// File not uploaded
            				$errorMsg = 'There was a problem uploading the file.';
            				$hook->addError($sf, $errorMsg);
            				$output = false; // generate submission error
            			}
                	
                	} else {
            			// File type not allowed
                	    $errorMsg = 'Type of file not allowed.';
            			$hook->addError($sf, $errorMsg);
            			$output = false; // generate submission error
                    }
            	
            	// if no file, don't error, but return blank
            	} else {
            	    $hook->setValue($sf, '');
            	}
            
            }
            
            return $output;
            
            ?>
            
              • 20178
              • 82 Posts
              hi this is great - im currently trying to use this in conjunction with the login - update profile section - im using it to allow a user to upload a photo that will be emailed to the client and also upoaded to a folder on the server -

              I see you say that you can create a unique date folder i would like to be able to create that folder as the user name and also name the file something like; usernamepimage - just to make it clear -
              and then grab it at a later date;

              can you advise the best method.

              the below just throws up errors;


              $uploadpath = ’assets/uploads/[’username’]’
                • 20178
                • 82 Posts
                worked this out in the end.... for anyone else that would like to name the pic after the user...

                <?php
                
                // initialize output;
                $output = true;
                  // get the current user name to create the file name as  
                $userName = $modx->user->get('username');
                
                // valid extensions
                $ext_array = array('pdf', 'txt', 'doc', 'docx', 'rtf', 'jpg');
                
                // create unique path for this form submission
                $uploadpath = 'assets/uploads/';
                
                // you can create some logic to automatically
                // generate some type of folder structure here.
                // the path that you specify will automatically
                // be created by the script if it doesn't already
                // exist.
                
                // EXAMPLE:
                // this would put all file uploads into a new,
                // unique folder every day.
                // $uploadpath = 'assets/'uploads/'.date('Y-m-d').'/';
                
                // get full path to unique folder
                $target_path = $modx->config['base_path'] . $uploadpath;
                
                // get uploaded file names:
                $submittedfiles = array_keys($_FILES);
                
                // loop through files
                foreach ($submittedfiles as $sf) {
                
                  // Get Filename and make sure its good.
                  $filename = basename( $_FILES[$sf]['name'] );
                
                  // Get file's extension
                  $ext = pathinfo($filename, PATHINFO_EXTENSION);
                  $ext = mb_strtolower($ext); // case insensitive
                
                  // is the file name empty (no file uploaded)
                  if($filename != '') {
                      
                    // is this the right type of file?
                    if(in_array($ext, $ext_array)) {
                      
                      //create file called the user name + pic
                      $filename = $userName . "pic".'.'.$ext  ;
                 
                      // full path to new file
                      $myTarget = $target_path . $filename;
                      
                      // create directory to move file into if it doesn't exist
                      mkdir($target_path, 0755, true);
                      
                      // is the file moved to the proper folder successfully?
                      if(move_uploaded_file($_FILES[$sf]['tmp_name'], $myTarget)) {
                        // set a new placeholder with the new full path (if you need it in subsequent hooks)
                        $modx->setPlaceholder('fi.'.$sf.'_new', $myTarget);
                        // set the permissions on the file
                        if (!chmod($myTarget, 0644)) { /*some debug function*/ }
                        
                          } else {
                        // File not uploaded
                        $errorMsg = 'There was a problem uploading the file.';
                        $hook->addError($sf, $errorMsg);
                        $output = false; // generate submission error
                      }
                      
                      } else {
                      // File type not allowed
                          $errorMsg = 'Type of file not allowed.';
                      $hook->addError($sf, $errorMsg);
                      $output = false; // generate submission error
                        }
                  
                  // if no file, don't error, but return blank
                  } else {
                      $hook->setValue($sf, '');
                  }
                
                }
                
                return $output;
                
                ?>

                • Hey!

                  I am using formit2resource and formit2files.

                  The formit2 resource always works fine and creates a resource, then sends the email.
                  But formit2files works only if i submit a form a second time after first submit.

                  The successfull redirect also works only on the second submit.

                  What might be the case?
                    modx and ecommerce pro
                    • 17546
                    • 75 Posts
                    Hello,

                    I use the formit2files (the mutliple files version), it work fine, but, when I use also the redirect hook, the form is not redirect to the Id I mention with the redirectTo parameter, when I remove the formit2files hook, it work perfectly, how to redirect when the form is sended and using the formit2files hook ?

                    low

                      Low
                      • 36625
                      • 2 Posts
                      I am using the multiple upload formit2file to upload a file to the website.

                      My aim is to upload an image and have the image location sent in the email.

                      When I use the:

                      &hooks=`math,spam,formit2file,email,redirect`



                      the file uploads but the form fails to send: "An error occurred while trying to send the email. File Error: Could not open file: /tmp/phpy8VLRj". The image uploads fine but form fails to send.

                      Now if I swap the hook call so that formit2file appears last:

                      &hooks=`math,spam,email,redirect,formit2file`


                      the form sends and everything else works perfectly, but because the email is sent before formit2file is called, the image placeholder/link in the email is not filled in, obviously because it is called after the email is sent.

                      Any reason why the formit2file hook is throwing this error when placed before email?