Yaws and File Upload
The example at yaws web site to read the file upload is a good starting point but it's too simplistic. I extended the example so it's useful in the real world. (Update: Thanks to Steve Vinoski, this module(yaws_multipart) is now part of the yaws git tree).
- It reads all parameters – files uploaded and other simple parameters .
- It takes a few options to help file uploads. Specifically:
- {max_file_size, MaxBytes} : If file exceeds MaxBytes bytes, return an error
- no_temp_file: read the uploded file in memory without any temp files
- {temp_file,FullFilePath}: Specify full path for the temp file. If not given, a unique file name is generated
- {temp_dir, TempDir} : Specify a directory to store uploaded temp file. By default '/tmp' is used.
Using it is simple. Just call read_multipart_form from your 'out' function and it'll return a tuple with first element either 'get_more', 'done' or 'error'. The 'get_more' implies more data needs to be read and you must call read_multipart_form again. 'done' implies it's done reading all parameters and you're free to proceed. The 'done' tuple also returns a 'dict' full of params. This dict can be queried for parameters by name. For file upload parameters it returns one of the following lists:
[{filename, "name of the uploaded file as entered on the form"}, {value, Contents_of_the_file_all_in_memory}] OR [{filename, "name of the uploaded file as entered on the form"}, {temp_file, "full pathname of the temp file"}]
In the second case, it's your responsibility to remove the temp file. Usage example:
-module(my_yaws_controller). -export([out/1]). out(Arg) -> Options = [no_temp_file], case yaws_multipart:read_multipart_form(Arg, Options) of {done, Params} -> io:format("Params : ~p",[Params]), [{filename, File_name},{value,File_content}] = dict:find("my_file", Params), Another_param = dict:find("another_param", Params); % do something with File_name, File_content and Another_param {error, Reason} -> io:format("Error reading multipart form: ~s", [Reason]); Other -> Other end .

May 7th, 2010 at 12:45 pm
Thank you fort this post, it helped me a lot! Uploading to yaws is now easy using read_multipart_form.