File Uploading Library

revIgniter's File Uploading Library permits to upload either a single file or multiple files. You can set various preferences, restricting the type and size of the files.

The Process

Uploading a file involves the following general process (single file example):

To demonstrate this process here is brief tutorial. Afterward you'll find reference information.

Creating the Upload Form

Using a text editor, create a form called uploadFormView.lc. In it, place this code and save it to your applications/views/ folder:

<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8">

    <title>[[gData["pageTitle"] ]]</title>

  </head>
  <body>

  [[gData["uploadError"] ]]

  [[gData["formOpen"] ]]

  [[gData["input"] ]]

  <br><br>

  [[gData["submit"] ]]

  </form>

  </body>
</html>

You'll notice we have a gData["formOpen"] variable which is declared in the controller using a form helper to create the opening form tag. File uploads require a multipart form, so the helper creates the proper syntax for you. You'll also notice we have a gData["uploadError"] variable. This is so we can show error messages in the event the user does something wrong.

The Success Page

Using a text editor, create a form called uploadSuccessView.lc. In it, place this code and save it to your applications/views/ folder:

<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8">

    <title>[[gData["pageTitle"] ]]</title>
	
  </head>
  <body>

    <h3>Your file was successfully uploaded!</h3>

    <? put "<ul>" into tUploadData
    repeat for each key tKey in gData["uploadData"]
      put gData["uploadData"][tKey] into tVal
      put "<li>" & tKey & ":" && tVal & "</li>" after tUploadData
    end repeat
    put "</ul>" after tUploadData
    return tUploadData ?>

    <p>[[gData["uploadLink"] ]]</p>

  </body>
</html>

The Controller

Using a text editor, create a controller called upload.lc. In it, place this code and save it to your applications/controllers/ folder:

<?lc

put "doUpload,buildForm,upload,index" into gControllerHandlers

command upload
  put "form,url" into tHelpers
  rigLoadHelper tHelpers

  # SET PAGE TITLE
  put "Upload Form" into gData["pageTitle"]
end upload


command index
  buildForm

  # LOAD THE VIEW FILE
  get rigLoadView("uploadFormView")
end index


command buildForm
  put rigFormOpenMultiPart("upload/doUpload") into gData["formOpen"]

  put "userfile" into tData["name"]
  put "20" into tData["size"]
  put rigFormUpload(tData) into gData["input"]

  put rigSubmitButton("uploadBtn", "upload") into gData["submit"]
end buildForm


command doUpload
  put "./uploads/" into tConfig["UploadPath"]
  put "gif|jpg|png" into tConfig["AllowedTypes"]
  put 100 into tConfig["MaxSize"]
  put 1024 into tConfig["MaxWidth"]
  put 768 into tConfig["MaxHeight"]

  rigLoaderLoadLibrary "Upload", tConfig

  rigDoUpload

  if the result is FALSE then
    put rigDisplayUploadErrors() into gData["uploadError"]

    buildForm

    # LOAD THE VIEW FILE
    get rigLoadView("uploadFormView")
  else
    put rigUploadData() into gData["uploadData"]
    put rigAnchor("upload", "Upload Another File!") into gData["uploadLink"]

    # LOAD THE VIEW FILE
    get rigLoadView("uploadSuccessView")
  end if
end doUpload

--| END OF upload.lc
--| Location: ./application/controllers/upload.lc
----------------------------------------------------------------------

The Upload Folder

You'll need a destination folder for your uploaded images. Create a folder at the root of your revIgniter installation called uploads and set its file permissions to 777.

Try it!

To try your form, visit your site using a URL similar to this one:

example.com/index.lc/upload/

You should see an upload form. Try uploading an image file (either a jpg, gif, or png). If the path in your controller is correct it should work.

Uploading Multiple Files

The process to upload multiple files (directories) is similar to the one outlined above with a few exceptions.

Following modifications of the sample code above needed to upload multiple files:
The controller needs a new buildForm handler and an additional line of code to check for upload errors in the doUpload handler. If you like you can set a limit for the maximum number of files allowed to be uploaded as shown below.

command buildForm
  put rigFormOpenMultiPart("upload/doUpload") into gData["formOpen"]

  put "userfile[]" into tData["name"]
  put "userfile" into tData["id"]
  put "20" into tData["size"]
  put "" into tData["multiple"]
  put "" into tData["directory"]
  put "" into tData["webkitdirectory"]
  put "" into tData["mozdirectory"]
  put rigFormUpload(tData) into gData["input"]

  put rigSubmitButton("uploadBtn", "upload") into gData["submit"]
end buildForm


command doUpload
  put "./uploads/" into tConfig["UploadPath"]
  put "gif|jpg|png" into tConfig["AllowedTypes"]
  put 100 into tConfig["MaxSize"]
  put 1024 into tConfig["MaxWidth"]
  put 768 into tConfig["MaxHeight"]
  put 5 into tConfig["MaxUploadFiles"]

  rigLoaderLoadLibrary "Upload", tConfig

  rigDoUpload

  if the result is FALSE then
    put rigDisplayUploadErrors() into gData["uploadError"]

    buildForm

    # LOAD THE VIEW FILE
    get rigLoadView("uploadFormView")
  else
    put rigDisplayUploadErrors() into gData["uploadError"]
    put rigUploadData() into gData["uploadData"]
    put rigAnchor("upload", "Upload Another File!") into gData["uploadLink"]

    # LOAD THE VIEW FILE
    get rigLoadView("uploadSuccessView")
  end if
end doUpload

Note: The name of the input field needs brackets as suffix.

The repeat loop of the success page needs to be adjusted like:

[[gData["uploadError"] ]]
		
<h3>File(s) successfully uploaded:</h3>

<? put the keys of gData["uploadData"] into tDataKeys
   rigSort tDataKeys, "ascnum"
      
   repeat for each line tItem in tDataKeys
     put "<p>--------------</p>" after tUploadData
     put "<ul>" after tUploadData
     repeat for each key tKey in gData["uploadData"][tItem]
       put gData["uploadData"][tItem][tKey] into tVal
       put "<li>" & tKey & ":" && tVal & "</li>" after tUploadData
     end repeat
   put "</ul>" after tUploadData
          
   end repeat 
   return tUploadData ?>

Note: There is an additional section for upload errors.

 

Reference Guide

Loading the Upload Library

Like most other libraries in revIgniter, the Upload library is loaded in your controller using the rigLoaderLoadLibrary command:

rigLoaderLoadLibrary "Upload"

Setting Preferences

Similar to other libraries, you'll control what is allowed to be uploaded based on your preferences. In the controller you built above you set the following preferences:

put "./uploads/" into tConfig["UploadPath"]
put "gif|jpg|png" into tConfig["AllowedTypes"]
put 100 into tConfig["MaxSize"]
put 1024 into tConfig["MaxWidth"]
put 768 into tConfig["MaxHeight"]

rigLoaderLoadLibrary "Upload", tConfig

# Alternately you can set preferences by calling the rigInitializeUpload command. Useful if you auto-load the library:
rigInitializeUpload tConfig

The above preferences should be fairly self-explanatory. Below is a table describing all available preferences.

Preferences

The following preferences are available. The default value indicates what will be used if you do not specify that preference.

Preference Default Value Options Description
uploadPath None None The path to the folder where the upload should be placed. The folder must be writable and the path must be relative to the root of your revIgniter installation.
allowedTypes None None The mime types corresponding to the types of files you allow to be uploaded. Usually the file extension can be used as the mime type. Separate multiple types with a pipe. Use a wildcard "*" to allow all types.
fileName None Desired file name

If set revIgniter will rename the uploaded file to this name. The extension provided in the file name must also be an allowed file type.

overwrite FALSE TRUE/FALSE If set to true, if a file with the same name as the one you are uploading exists, it will be overwritten. If set to false, a number will be appended to the filename if another with the same name exists.
maxSize 0 None The maximum size (in kilobytes) that the file can be. Set to zero for no limit.
maxWidth 0 None The maximum width (in pixels) that the file can be. Set to zero for no limit.
maxHeight 0 None The maximum height (in pixels) that the file can be. Set to zero for no limit.
maxFilename 0 None The maximum length that a file name can be. Set to zero for no limit.
encryptName FALSE TRUE/FALSE If set to TRUE the file name will be converted to a random encrypted string. This can be useful if you would like the file saved with a name that can not be discerned by the person uploading it.
removeSpaces TRUE TRUE/FALSE If set to TRUE, any spaces in the file name will be converted to underscores. This is recommended.
maxUploadFiles 0 None The maximum number of files allowed to be uploaded. Set to zero for no limit.
xssClean FALSE TRUE/FALSE Enables the XSS flag so that the file that was uploaded will be run through the XSS filter.

Setting preferences in a config file

If you prefer not to set preferences using the above method, you can instead put them into a config file. Simply create a new file called upload.lc, add the Config array in that file. At the end of the file write: rigRunInitialUploadConfig yourArrayVariableName. Then save the file at config/upload.lc and it will be used automatically. You will NOT need to use the rigInitializeUpload command if you save your preferences in a config file. Example:

local sUploadConf

put "./uploads/" into sUploadConf["UploadPath"]
put "gif|jpg|png" into sUploadConf["AllowedTypes"]
put 100 into sUploadConf["MaxSize"]
put 1024 into sUploadConf["MaxWidth"]
put 768 into sUploadConf["MaxHeight"]
put 5 into sUploadConf["MaxUploadFiles"]

rigRunInitialUploadConfig sUploadConf

Handler Reference

The following handlers are available

rigDoUpload

Performs the upload based on the preferences you've set. Note: By default the upload routine expects the file to come from a form field called userfile, and the form must be a "multipart type:

<form method="post" action="some_action" enctype="multipart/form-data" />

If you would like to set your own field name simply pass its value to the rigDoUpload command:

put "someFieldName" into tFieldname
rigDoUpload tFieldname

rigDisplayUploadErrors()

Retrieves any error messages if the rigDoUpload command returned false. The function does not write to the page automatically, it returns the data so you can assign it however you need.

Formatting Errors

By default the above function wraps any errors within <p> tags. You can set your own delimiters like this:

rigDisplayUploadErrors("<p>", "</p>")

rigUploadData()

This is a helper function that returns an array containing all of the data related to the file you uploaded. Here is a prototype of the array returned:

tData["FileName"] # => mypic.jpg
tData["FileType"] # => image/jpeg
tData["FilePath"] # => /path/to/your/upload/
tData["FullPath"] # => /path/to/your/upload/jpg.jpg
tData["RawName"] # => mypic
tData["OrigName"] # => mypic.jpg
tData["ClientName"] # => mypic.jpg
tData["FileExt"] # => .jpg
tData["FileSize"] # => 22.2
tData["IsImage"] # => TRUE
tData["ImageWidth"] # => 800
tData["ImageHeight"] # => 600
tData["ImageType"] # => jpeg
tData["ImageSizeStr"] # => height="600" width="800"

In case multiple files were uploaded this data is returned in a numbered array like:

tData[tFileNumber]["FileName"] # => mypic.jpg
tData[tFileNumber]["FileType"] # => image/jpeg
tData[tFileNumber]["FilePath"] # => /path/to/your/upload/
tData[tFileNumber]["FullPath"] # => /path/to/your/upload/jpg.jpg
tData[tFileNumber]["RawName"] # => mypic
tData[tFileNumber]["OrigName"] # => mypic.jpg
tData[tFileNumber]["ClientName"] # => mypic.jpg
tData[tFileNumber]["FileExt"] # => .jpg
tData[tFileNumber]["FileSize"] # => 22.2
tData[tFileNumber]["IsImage"] # => TRUE
tData[tFileNumber]["ImageWidth"] # => 800
tData[tFileNumber]["ImageHeight"] # => 600
tData[tFileNumber]["ImageType"] # => jpeg
tData[tFileNumber]["ImageSizeStr"] # => height="600" width="800"

Explanation

Here is an explanation of the above array items.

ItemDescription
FileName The name of the file that was uploaded including the file extension.
FileType The file's Mime type.
FilePath The absolute server path to the file.
FullPath The absolute server path including the file name.
RawName The file name without the extension.
OrigName The original file name. This is only useful if you use the encrypted name option.
ClientName The file name as supplied by the client user agent, prior to any file name preparation or incrementing.
FileExt The file extension with period.
FileSize The file size in kilobytes.
IsImage Whether the file is an image or not. TRUE = image. FALSE = not.
ImageWidth Image width.
ImageHeight Image height.
ImageType Image type. Typically the file extension without the period.
ImageSizeStr A string containing the height and width. Useful to put into an image tag.