Tuesday, April 16, 2013

How to upload file using jsp using FileRenamePolicy

How to upload file from jsp?Java servlet  API doesn't provide any class to handle file upload.So we have to download external library to upload file Download Jar.File uploading can be done only with doPost and by using enctype "multipart/form-data" .By default it's enctype is"application/x-www-form-urlencoded" Feature of various enctype given below

valueDescription
application/x www form urlencodedSpace of url converted to "+" symbols and special characters are converted into ASCII HEX values.All characters are encoded before sent
mulipart/form-dataValue is required when you are using rms that have a file upload file contol(no characters are encoded)
text/plainSpaces are converted into "+" symbols.No specical character are encoded.
The Structure of form is like
<form name="form" method="post" enctype="multipart/form-data"action="YourController">
        <input  type="file"  name="file" size="50" />              
        <input  type="submit" name="Insert" value="Insert">
</form>
Coding at Controller
protected void doPost(HttpServletRequest request,HttpServletResponse response) throws ServletException, IOException {
if (ContextType.indexOf("multipart/form-data") >= 0) {
    MultipartRequest m = new MultipartRequest(request, "yourpath");
    m.getOriginalFileName("file") ;//return the name of uploaded file  
   } 
}
MultipartRequest Constructor have 
MultipartRequest(HttpServletRequest request, String saveDirectory,int maxPostSize,String encoding,FileRenamePolicy policySource Code
  • request the servlet request.
  • saveDirectory the directory in which to save any uploaded files.
  • maxPostSize the maximum size of the POST content.
  • encoding the encoding of the response, such as ISO-8859-1
  • policy a pluggable file rename policy
File rename policy is used to rename a file,Suppose you upload a file but in upload folder, file existed with same name,then it cause overwrite the old file with new one.So solution is to use File rename policy
  • It automatically add number to file name
  • Example sample.txt ,sample1.txt,sample2.txt and so on
import com.oreilly.servlet.multipart.DefaultFileRenamePolicy;
MultipartRequest m = new MultipartRequest(request, Path, 5024 * 1024, new DefaultFileRenamePolicy());
It automatically add number to filename.
But if you want to give name according to your standard then
MultipartRequest m = new MultipartRequest(request, Path,
                    5024 * 1024, new FileRenamePolicy() {
                        @Override
                        public File rename(File arg0) {
                            boolean result = arg0.renameTo(new File(arg0
                                    .getParentFile().getAbsolutePath()
                                    + File.separator + "Standard"));
                            if (result) {
                                System.out.println("Renamed");
                            }
                            return arg0;
                        }
                    });

But file.renameTo() have unpredictable behaviour on Windows, it seems. As the API documentation says,

Many aspects of the behavior of this method are inherently platform-dependent: The rename operation might not be able to move a file from one filesystem to another, it might not be atomic, and it might not succeed if a file with the destination abstract pathname already exists. The return value should always be checked to make sure that the rename operation was successful.

You can use apache.commons.io library, which includes FileUtils.moveFile() or also the Files.move() method in JDK 7.

At bottom line we can successfully use DefaultFileRenamePolicy on windows.If you have any Confusion or any doubt then leave a message below or email me 
 

13 comments :

Post a Comment