This task demonstrates how to handle multipart/form-data form submits by creating two web scripts for the following functions:
- Present a form that allows the selection of a file along with title and description
- Upload the selected file into the repository
Your sample form consists of only three input fields, where one is of type file. The form posts its content to the action URI as identified by the root object url.service, which for this sample is /multipart and specifies the multipart/form-data content type.
... <formaction="${url.service}"method="post"enctype="multipart/form-data"> ...
Your two web scripts are mapped to the same URI. However, the form is attached to the HTTP GET method and the upload is attached to the HTTP POST method, which allows your form to post to the same URI as the form itself.
When multipart/form-data is posted to a web script, the Web Script Framework provides a special root object named formdata that allows access to the posted request through a simple API, hiding the complexities of parsing the request directly. The API provides access to each form field, including its name and value. For form fields of type file, the content of the uploaded file is also provided. To simplify even further, all fields other than those of type file are also added to the root objects args and argsM. Your upload web script extracts the form title and description fields from the args root object and locates the uploaded file through the formdata root object.
... var title = args.title; var description = args.description; var file = null; for each (field in formdata.fields) { if (field.name == "file" && field.isFile) { file = field; } } ...
If a file has been uploaded, the upload web script creates a new document within the Alfresco content repository under the Company Home folder. The document is named after the file name of the uploaded file and its content is taken from the file content.
... upload = companyhome.createFile(file.filename) ; upload.properties.content.guessMimetype(file.filename); upload.properties.content.write(file.content); ...
The created document is placed into the web script model, allowing the upload response template to render a message confirming the name and size of the uploaded file.
... model.upload = upload; ...