Wednesday, October 31, 2012

Servlet 3.0 and HTML 5 File Upload Servlet Example

Someone asked how simple is it to create a servlet using 3.0 technology which could upload a file. It took me about 5 minutes to do using NetBeans 7.2, and another 10 minutes to tweak for the file name. I hope that this proves how quick and easy it is to do. The code is also very readable.

Here is the code for my servlet, and form:


8 comments :

leming said...

Nice example. According path used in example, you are on unix based machine(Mac?) or linux. i am using win7 and i have sligthly changed code
@MultipartConfig(location="C:/temp")
works fine, except it breaks cyrylic filenames but it is a encoding issue.
thanks

John Yeary said...

You are correct sir! I am using a Mac. Thanks for the additional information for Windows users.

Unknown said...

i wonder in case when the big files are uploaded, will the parts be available when all the content is parsed & saved/cache somewhere by the jvm or or they streamed ?

thanx

John Yeary said...

I have not tried it on any large files. There are usually practical limits to uploading files using an HTML uploader. If you have some large files to upload, I would be interested in seeing what difficulties if any that you encounter.

The example was not meant to be a complete solution. It was a simple demonstration of what is possible.

Unknown said...

sorry not to be more specific in my question.

if there're 2 files in the form to be uploaded, will this line:

for (Part part : request.getParts()) ...

get hit right after the first part comes to server of after both files have already landed/transfered to the webserver ?

thanx.

Unekwu said...

@Kim From John's code, all the files are sent to the server at the same time and processed in the loop. So every file found in the multipart object is written to the server.

Also you can write individual files by doing
Part multipartfile = request.getPart("filename");
multipartfile.write(new File("/interesting/location/file"))

John Yeary said...

The code for uploading depends on the browser for uploads. Some allow multiple uploads, and some don't.

For some examples of file uploaders see my other posts.

http://javaevangelist.blogspot.com/2011/12/multiple-file-upload-examples.html

http://javaevangelist.blogspot.com/2010/12/multiple-file-upload-options.html

John Yeary said...

Thanks for adding information @Unekwu which is more clarifying.

Popular Posts