upload

Description

Wpart responsible for uploading the files from the localhost to the server.

Including this wpart in the custom type will trigger adding the multipart="multipart" attribute to the form that surrounds the input tag.

The uploaded file is stored in the temporary directory (which will be removed after processing the request), so the file must be copied by the controller itself. From controller point of view, the value of the field is the absolute path to the temporary file.

Erlang Web framework provides the useful function for moving the file to the permanent directory: e_file:copy(SourcePath, DestSubdir) where SourcePath is the value of the field (absolute path to the uploaded file) and DestSubdir is a subdirectory inside the upload directory (placed inside the docroot and defined in the project.conf file). The returned value is the absolute path to the copied file (so it can be saved in the database).

The useful function is also e_file:get_relative_name(Path) that returns the path to the file that could be embed inside the HTML (relative to the docroot folder).

In case of editing the entity the input field is empty, however there is a comment with the link to the previously uploaded file displayed. If user lefts the field empty, the file will not be overridden. Otherwise new file will be sent. Unfortunately, there is no way other than deleting the file by hand to remove the uploaded file from the server.

The rendered widget is <input type="upload" ... />.

Validation

option

format

description

error message

extensions

[Ext1, Ext2, ...]

Specifies a list of valid extensions for the uploaded file. Note that extension is checked on the server side, so the file must be uploaded anyway. The extensions are case insensitive.

{bad_extension, Filename}

max_size

Size :: integer() or {Size :: integer(), bytes | kbytes | mbytes}

Defines the maximum size of the uploaded file. If only number is provided, the validator assumes the size is in bytes.

{too_big, Filename}

Examples

Records definitions

...
{upload, [{extensions, ["jpg", "gif", "jpeg"]},
          {max_size, {3, mbytes}}
          %% other parameters
         ]
},
...

HTML tag

<wpart:upload OTHER_HTML_ATTRIBUTES />

Controller

create(BlogPost) ->
  Filename = case BlogPost#blog_post.image of
               undefined ->
                 undefined;
               F ->
                 e_file:copy(F, "post_images")
              end,

  e_db:write(posts, BlogPost#blog_post{id = e_db:get_next_id(posts),
                                       image = Filename}).

Wparts/BasicTypes/upload (last edited 2009-02-25 08:40:47 by Michal Ptaszek)