Sunday, March 10, 2013

Handling Multiple File Uploads in a Go Web Application

It took me some time to get this right as I couldn't find an easy-to-follow example on the web. Since this is a common use case, this post may hopefully help someone.

This example has a single template for the main webpage that has the file upload form. The backend handler serves this template on a GET request and handles the upload on a POST request. If you're not familiar with Go's html templates, I would recommend reading this well written document first.

The uploadHandler method is where the action happens. This handler responds to a GET request by displaying the upload form. This form POSTs to the same URL - the handler responds by parsing the posted form, saving the uploaded files and displaying a success message.

You can find the complete project at - https://github.com/sanatgersappa/Go-MultipleFileUpload

Update: As pointed out by Luit in the comments, an alternate way of doing this is to use a mime/multipart.Reader exposed by r.MultipartReader() instead of r.MultiparseForm(). This approach has the advantage that it doesn't write to a temporary location on the disk, but processes bytes as they come in.