I am trying to upload images onto a shared hosting server (Tomcat 6), using multipart/form-data POST request and org.apache.commons.fileupload API.
After the program extract the images from the multipart/form-data, it writes them to disk using the following code:
config.getServletContext().getRealPath("/"+"Uploaded_Images") returns the follwoing path to which the file should be written to "/home/donnarosa/web-root/Uploaded_Images".
However tomcat throws the following error:
Why the hell is Tomcat 6 trying to write the file to /home/tomcat/default/temp/upload_18249544_124a245f512__7ff4_00000062.tmp, this is tomcat default temporary directory. I specifically tell it to write to "/home/donnarosa/web-root/Uploaded_Images". It is like it completely ignores the path that i specify.
I asked hosting support about this and that what they replied:
it seems to me that you're trying to use the tomcat default temporary directory.
Your application is not allowed to write there as this is a security risk. You should use a directory which is under your home directory. E.g. create /home/donnarosa/tmp and do a
chmod a+w tmp
I think I am slowly beging to understand what is wrong.
According to apache commons:
What happens during the file upload is that the files are first stored temporarily on disk on the server. "Is this right?"
And the repository into which they are stored temporarily into, is set to system default temp directory.
In my case, the default repository will be "/home/tomcat/default/temp/upload_18249544_124a245f512__7ff4_00000062.tmp".
Thats why I get Access Denied error becasue it is a security risk to write to this folder and the hosting company blocks writing to this folder.
So David Newton was right at suggesting that commons-fileupload saves the files first to temp directory and then to the directory that you specify. I didn't realise that was the case.
So to solve the problem, we need to change the default repository dir from default to root location on the server:
First create tmp folder in you root dir.
Second change the repsitory using the following code:
DiskFileItemFactory factory = new DiskFileItemFactory();
Now the file will be attempted to be writen to new temp dir.
I still get an error and cannot write to /tmp because there are now write permissions set for this folder, so I contacted hosting support to enable write permissions.
Why not make the temporary directory something you can write to? Like your hosting account, or something in the web app (which might not work, depending on how you're deploying and other factors). IIRC you can also set this in a properties file.
I'm moving this to a more appropriate forum, as it's not really JSP-related.
If it's the same error, then you simply can't write files into your webapp. Note that putting images there is somewhat risky, depending on how your ISP operate--a redeploy might just delete them all. IMO uploaded images should be saved outside the webapp, and retrieved with an image servlet.