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:
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
ReplyDelete@MultipartConfig(location="C:/temp")
works fine, except it breaks cyrylic filenames but it is a encoding issue.
thanks
You are correct sir! I am using a Mac. Thanks for the additional information for Windows users.
ReplyDeletei 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 ?
ReplyDeletethanx
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.
ReplyDeleteThe example was not meant to be a complete solution. It was a simple demonstration of what is possible.
sorry not to be more specific in my question.
ReplyDeleteif 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.
@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.
ReplyDeleteAlso you can write individual files by doing
Part multipartfile = request.getPart("filename");
multipartfile.write(new File("/interesting/location/file"))
The code for uploading depends on the browser for uploads. Some allow multiple uploads, and some don't.
ReplyDeleteFor 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
Thanks for adding information @Unekwu which is more clarifying.
ReplyDelete