Wednesday, November 18, 2009

File Upload in Portlets

If you are writing a web application rather than a website you might want to upload files to the server. An example is where the user might have a set of files in his/her filespace that he/she wishes to load and run on the server somehow. But how to do it?

First Shot

Since HTML has a nice <input type="file"/> element, why not use that? If you try it you'll find that when the user posts the form containing the file input field, that only the file name, not its path gets passed to the server. So you can't open the file and do anything with it unless you have predestined knowledge about where it is. This is a security measure so that the servlet designer doesn't get privileged information about the user's hard disk structure and contents. Security 1 Webapp Designers 0.

Second Attempt

I read somewhere that if you use a POST form with an enctype="multipart/form-data" attribute that the form will post the full path name. Cool! I tried that but in my portlet when I examine the parameters passed in the processAction method I get zero parameters, even if there are other parameters besides the file input field. Great! Back to square one.

Third Go

Then I read that if you process the ActionRequest using the Apache fileupload facility you can recover the input file param and the other params. This complicates things but seems to be the way Microsoft get around the restriction in their web Outlook client. So I tried it too. Only problem is that you don't even then get the full path of the original file but the path to the uploaded file. But you can still read it, which is all you need I guess. Since my files are all small XML files this doesn't matter.