Link to home
Start Free TrialLog in
Avatar of leogc
leogc

asked on

File Upload using JSP

I want to attach a file of maximum size 2MB.How to do file attachment on click of button and how to check for the size of the file to be less than 2MB.
Avatar of bloodredsun
bloodredsun
Flag of Australia image

Use FileUpload from jakarta http://jakarta.apache.org/commons/fileupload

The maximum file size can be set along with other settings in the receiving servlet

-----------
// Create a factory for disk-based file items
DiskFileItemFactory factory = new DiskFileItemFactory();

// Set factory constraints
factory.setSizeThreshold(yourMaxMemorySize);
factory.setRepositoryPath(yourTempDirectory);

// Create a new file upload handler
ServletFileUpload upload = new ServletFileUpload(factory);

// Set overall request size constraint --  HERE
upload.setSizeMax(yourMaxRequestSize);

// Parse the request
List /* FileItem */ items = upload.parseRequest(request);
Avatar of thomas908
thomas908

Avatar of leogc

ASKER

Thanks for the reply.I went through the contents of website  http://jakarta.apache.org/commons/fileupload
.But i want more detailed explanation of customising File Upload through jakarta commons file upload.I tried a sample program of uploading file through whatever the code u have mentioned here.But it displays some popup
message before uploading which I dont want or rather customise the file upload functionality.
Regards
Leo
What was the pop up message?
Avatar of leogc

ASKER

While I am trying to upload the file from browser to the database,it is showing the dialog box of the file download i.e Would you like to open the file or save it to computer and my snippet of servlet code is as follows:
public void doPost(HttpServletRequest req,HttpServletResponse res)throws
      ServletException,IOException
      {
            res.setContentType("multipart/form-data");
            PrintWriter pw=res.getWriter();
                     fileUploadHandler(req);
      
      }
      void fileUploadHandler(HttpServletRequest req){
            
            // Create a factory for disk-based file items
            FileItemFactory factory = new DiskFileItemFactory();
      
            // Create a new file upload handler
            ServletFileUpload upload = new ServletFileUpload(factory);
      
            // Parse the request
            try{
      
                  List  items = upload.parseRequest(req);
      
            }catch(Exception e){
                        System.out.println("error"+e.getMessage());
                        e.printStackTrace();
                  }
      }
Why are you getting the writer?
Avatar of leogc

ASKER

Even if I remove the writer the same File download dialog box is appearing.
One more thing is how to get the file name of the uploaded file in the servlet handling the uploaded file.I tried the following code snippet specified in one of the links provided in this site.But it is going to infinite loop at the line pos = fileData.indexOf("filename=\"", startPos);

code snippet:
int formDataLength=request.getContentLength();
      byte dataBytes[]=new byte[formDataLength];
      byte[] line=new byte[128];
      int count=0;
      String s="";
      String fileData="";
      int pos=0;
      int startPos=0;
      int endPos=0;
do  
  {  
   copyByte(dataBytes, line, count ,1); //read 1 byte at a time  
   count+=1;  
   s = new String(line, 0, 1);  
   fileData = fileData + s;  
   pos = fileData.indexOf("filename=\"", startPos); //set the file name  
   if(pos != -1)  
    startPos = pos;  
  }while(pos == -1);
 
void copyByte(byte [] fromBytes, byte [] toBytes, int start, int len)  
      {  
        for(int i=start;i<(start+len);i++)  
         {  
            toBytes[i - start] = fromBytes[start];  
         }  
      }
please post your entire code and I'l have a look on monday
Avatar of leogc

ASKER

My JSP page is common to both the questions i.e  (1)dialog box is appearing when I
Try to upload the file (2)how to get the filename of the uploaded file in file upload handler servlet.
jsp code
<html>
<head>
<script>
      function uploadfile()
       {
            form=document.forms[0];
            form.action="/samples/fileupload";
                  form.submit();
       }
</script>
</head>
<body>
<form method="post" enctype="multipart/form-data">
<font color="blue" size="5">Attach Files</font><br>
Click "Browse" to select a file.You can attach files up to a<br>
total message size of 2.0MB.<br>
File :<input type="file" name="file1"/><br>
<br><br>
<input type="button" value="Attach Files" onclick="uploadfile()"/>
</form>
</body>
</html>


1.Servlet code for first question.
package upload;
import javax.servlet.*;
import javax.servlet.http.*;
import java.io.*;
import java.util.*;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.FileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

public class FileUpload extends HttpServlet
{
      public void doPost(HttpServletRequest req,HttpServletResponse res)throws
      ServletException,IOException
      {
            res.setContentType("multipart/form-data");
            // Create a factory for disk-based file items
            FileItemFactory factory = new DiskFileItemFactory();
            // Create a new file upload handler
            ServletFileUpload upload = new ServletFileUpload(factory);
            try{
                  List  items = upload.parseRequest(req);
      
            }catch(Exception e){
                  System.out.println("error"+e.getMessage());
                  e.printStackTrace();
            }
      }
}



2.Servlet code for second question i.e. how to get the file name of  uploaded file.
package upload;
import javax.servlet.*;
import javax.servlet.http.*;
import java.io.*;
import java.util.*;

public class FileUpload extends HttpServlet
{
      public void doPost(HttpServletRequest req,HttpServletResponse res)throws
      ServletException,IOException
      {
            res.setContentType("multipart/form-data");
            int formDataLength=req.getContentLength();
            byte dataBytes[]=new byte[formDataLength];
            byte[] line=new byte[128];
            int count=0;
            String s="";
            String fileData="";
            int pos=0;
            int startPos=0;
            int endPos=0;
            String boundary="";
            String filename="";
            String strLocalFileName="";
            do  
                {  
                 copyByte(dataBytes, line, count ,1); //read 1 byte at a time  
                 count+=1;  
                 s = new String(line, 0, 1);  
                 fileData = fileData + s;  
                 pos = fileData.indexOf("Content-Disposition: form-data; name=\"");  
                 if(pos != -1)  
                  endPos = pos;  
              }while(pos == -1);  
              boundary = fileData.substring(startPos, endPos);  
            System.out.println("BOUNDARY"+boundary);
            do  
              {  
                     copyByte(dataBytes, line, count ,1); //read 1 byte at a time  
                     count+=1;  
                     s = new String(line, 0, 1);  
                     fileData = fileData + s;  
                     pos = fileData.indexOf("Content-Type: ", startPos);  
                     if(pos != -1)  
                      endPos = pos;  
                }while(pos == -1);  
              filename = fileData.substring(startPos + 10, endPos - 3);
            strLocalFileName = filename;  
            int index = filename.lastIndexOf("\\");  
            if(index != -1)  
            filename = filename.substring(index + 1);  
              else  
               filename = filename;  
            System.out.println("FILENAME"+filename);
      }
      void copyByte(byte [] fromBytes, byte [] toBytes, int start, int len)  
             {  
                for(int i=start;i<(start+len);i++)  
                 {  
                     toBytes[i - start] = fromBytes[start];  
                 }  
             }  
      
}

Avatar of leogc

ASKER

I didnt get any solution to the question what ever i had posted.What should i do to the question
While we wait for bloodredsun to get back here, maybe I can help you.
>1)dialog box is appearing when I Try to upload the file
That is surprising. I can't understand that.
>(2)how to get the filename of the uploaded file  
You can use the apache  code  for that. Use something like the following.
                        String filename = "file name from client";
                        for (int i = 0; i < items.size(); i ++) {
                              FileItem item = (FileItem) items.get(i);
                              if(item.isFormField()){
                              }
                               else  fileName = item.getName();
                        }                                                                    
Avatar of leogc

ASKER

can u throw some more light on whatever code u have sent in detail.I am not able to understand what is this u r talking about file name from client.My jsp contains a text field also. I want to retrieve that data also in my servlet.I forgot to mention that in my jsp.
The  getName method will give the name of the file that it had on the client's machine before it was uploaded. Just put it into your code something like this to test.

package upload;
import javax.servlet.*;
import javax.servlet.http.*;
import java.io.*;
import java.util.*;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.FileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
public class FileUpload extends HttpServlet
{
     public void doPost(HttpServletRequest req,HttpServletResponse res)throws  ServletException,IOException
     {
          res.setContentType("multipart/form-data");
          FileItemFactory factory = new DiskFileItemFactory();
          ServletFileUpload upload = new ServletFileUpload(factory);
          try{
               List  items = upload.parseRequest(req);
                        for (int i = 0; i < items.size(); i ++) {
                              FileItem item = (FileItem) items.get(i);
                              if(!item.isFormField()) System.out.println("file name is " + item.getName());
                        }                                                          
          }catch(Exception e){
               System.out.println("error"+e.getMessage());
               e.printStackTrace();
          }
     }
}
Avatar of leogc

ASKER

I am still getting the File Download dialog box after using
what ever code u have sent above.This is causing a lot of problem to me.Can anyone pls tell me why i am getting this dialog box.Does it depend on the OS.I am using Windows XP as OS.
>I am still getting the File Download dialog box after using  what ever code u have sent above.  
I can't explain it.  Hopefully bloodredsun will find time to help you.
Avatar of leogc

ASKER

hi
bloodredsun  any comments from u on why I am getting the file download dialog box will be greatly helpful to me.Do u people are also facing this problem?
Avatar of leogc

ASKER

I did not get any solution to this question regarding why the download dialog box is comming.What should be done to this question.
What version of FileUpload are you using ? Please post the minimum code that will show the behavior you describe. I will try to reproduce it on my machine.     rrz
Avatar of leogc

ASKER

I am using commons-fileupload-1.1.jar and commons-io-1.1.jar.My jsp page and servlet code are as follows:
jsp page:
<html>
<head>
<script>
      function uploadfile()
       {
            
            form=document.forms[0];
            form.action="/samples/fileupload";
                      form.submit();
       }
</script>
</head>
<body>
<form method="post" enctype="multipart/form-data">
<font color="blue" size="5">Attach Files</font><br>
Click "Browse" to select a file.You can attach files up to a<br>
total message size of 10.0MB.<br>
File 1:<input type="file" name="file1"/><br>
<input type="button" value="Attach Files" onclick="uploadfile()"/>
</form>
</body>
</html>


servlet code:
package upload;
import javax.servlet.*;
import javax.servlet.http.*;
import java.io.*;
import java.util.*;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.FileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

public class FileUpload extends HttpServlet
{
     public void doPost(HttpServletRequest req,HttpServletResponse res)throws
     ServletException,IOException
     {
          res.setContentType("multipart/form-data");
         
          FileItemFactory factory = new DiskFileItemFactory();
         
          ServletFileUpload upload = new ServletFileUpload(factory);
          try{
               List  items = upload.parseRequest(req);
     
          }catch(Exception e){
               System.out.println("error"+e.getMessage());
               e.printStackTrace();
          }
     }
}

Ok, I see the behavior that you describe. I can't explain it. Hopefully bloodredsun can explain. Please don't close this question until we get an explaination.  
I did come up with the following working code.   rrz  

package upload;
import javax.servlet.*;
import javax.servlet.http.*;
import java.io.*;
import java.util.*;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.*;
import org.apache.commons.fileupload.servlet.*;
public class leogc extends HttpServlet
{
     public void doPost(HttpServletRequest req,HttpServletResponse res)throws
     ServletException,IOException
     {          
       res.setContentType("text/html");
       PrintWriter out = res.getWriter();
       RequestContext reqContext = new ServletRequestContext(req);
       if(FileUploadBase.isMultipartContent(reqContext)){
          FileItemFactory factory = new DiskFileItemFactory();
          ServletFileUpload upload = new ServletFileUpload(factory);
          try{
               List  items = upload.parseRequest(reqContext);
               out.println("<html>");
               out.println("<head><title>File Upload</title></head>");
               out.println("<body>");
               out.println("Received file.");
               out.println("</body></html>");
          }catch(Exception e){
               System.out.println("error"+e.getMessage());
               e.printStackTrace();
          }
       } else{  
               out.println("<html>");
               out.println("<head><title>File Upload</title></head>");
               out.println("<body>");
               out.println("Problem at server.");
               out.println("</body></html>");
             }
     }
}
>I did not get any solution to this question regarding why the download dialog box is comming      
This lastest version of fileupload seems to be dependent on commons io ( where as version 1.0 was not).  
At first I thought that your omission of  
> res.setContentType("text/html");    
was the problem,but that didn't seem to solve it.    
Give points to whoever can explain.   rrz
I guess no one will help. Did you try my last code ?
Avatar of leogc

ASKER

No I have not tried yet.Give me some time.Assuming this code works what i am planning to do is get the file name,rename the file,build  a path on the server and store the renamed file in the directory created under the built path.Store the build path in the database.will it be possible to do the above with whatever the code u have sent.
>will it be possible to do the above with whatever the code u have sent.  
The code above just uploads the file. First get that working. I can help you with the rest as well.  But first look at the examples on the Jacarkta site. It shows how to get hold of the FileItem you want to use.
Avatar of leogc

ASKER

Thanks for the reply.The code which u sent has solved the problem of pop up window which was appearing.
Now i am trying to store the uploaded file in some directory on the server.Any inputs on how to upload
and store the file on the server will be helpful.
>Now i am trying to store the uploaded file in some directory on the server  
Please show your code. Did you add code to my posted code in order to get hold of the uploaded file ? Do you want to place file within your web app ?   Are you using something like the following ?
  FileWriter fw = new FileWriter(new File(application.getRealPath("/"),"uploadedFile.txt"));
where application is your web app's context.    
Avatar of leogc

ASKER

I have written the following servlet to upload the file and store it in some directory on server.Is there any way to optimize this code because I am using File class to get the filename and build the path and FileInputStream for reading the contents of the file.

Is this the way they do the file upload in realtime i.e build the output file path,read the
Input file contents and write to some location on the built server path.

One more thing I want to do now is restrict the size of the uploaded file.How to do this.


package upload;
import javax.servlet.*;
import javax.servlet.http.*;
import java.io.*;
import java.util.*;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.*;
import org.apache.commons.fileupload.servlet.*;
public class UploadServlet extends HttpServlet
{
     public void doPost(HttpServletRequest req,HttpServletResponse res)throws
     ServletException,IOException
     {
       res.setContentType("text/html");
       PrintWriter out = res.getWriter();
       String inputFileName;
       String outputFileName=null;
       String path;
       String filePart1;
       String filePart2;
       RequestContext reqContext = new ServletRequestContext(req);
       Properties props=System.getProperties();
            String fileSeparator=props.getProperty("file.separator");
            String serverPath=getServletContext().getRealPath(fileSeparator);
            String finalPath=serverPath+"temp";
            System.out.println("path is "+finalPath);

            File outFile=new File(finalPath);
            outFile.mkdir();
            File fc=outFile.getCanonicalFile();
            System.out.println("FILE NAME"+fc.getName());


       if(FileUploadBase.isMultipartContent(reqContext)){
          FileItemFactory factory = new DiskFileItemFactory();
          ServletFileUpload upload = new ServletFileUpload(factory);
          try{
                List  items = upload.parseRequest(reqContext);
                FileItem item = (FileItem) items.get(0);
                        path=item.getName();
                        File inFile=new File(path);
                        inputFileName=inFile.getName();
                        System.out.println("input file name is " + inputFileName);

                        filePart1=inputFileName.substring(0,inputFileName.lastIndexOf("."));
                        filePart2=inputFileName.substring(inputFileName.lastIndexOf("."));

                        if(fc.isDirectory()){
                            int j=fc.list().length;
                            outputFileName=filePart1+Integer.toString(j)+filePart2;
                        }
               /*out.println("<html>");
               out.println("<head><title>File Upload</title></head>");
               out.println("<body>");
               out.println("Received file.");
               out.println("</body></html>");*/
               System.out.println("file uploaded successfully "+outputFileName);

                        FileInputStream inputStream=new FileInputStream(path);

               FileOutputStream fout=new FileOutputStream(finalPath+"\\"+outputFileName);
                                 int i=0;
                                 while((i=inputStream.read())!=-1){
                                      fout.write(i);
                                 }
                                 fout.close();
                                 inputStream.close();

                     System.out.println("filein"+fc.list().length);
          }catch(Exception e){
               System.out.println("error"+e.getMessage());
               e.printStackTrace();
          }
       } else{
               /*out.println("<html>");
               out.println("<head><title>File Upload</title></head>");
               out.println("<body>");
               out.println("Problem at server.");
               out.println("</body></html>");*/
             }
     }
}
>One more thing I want to do now is restrict the size of the uploaded file.How to do this.
Did you see the  setSizeThreshold  method  of  DiskFileItemFactory  ?  
http://jakarta.apache.org/commons/fileupload/apidocs/org/apache/commons/fileupload/disk/DiskFileItemFactory.html
Avatar of leogc

ASKER

what about other parts of question i.e.the real time file upload and code optimisation.
Sorry, I have been very busy. You could this many ways. Here is an example.  
package upload;
import javax.servlet.*;
import javax.servlet.http.*;
import java.io.*;
import java.util.*;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.*;
import org.apache.commons.fileupload.servlet.*;
public class leogc extends HttpServlet
{
     public void doPost(HttpServletRequest req,HttpServletResponse res)throws
     ServletException,IOException
     {          
       res.setContentType("text/html");
       PrintWriter out = res.getWriter();
       RequestContext reqContext = new ServletRequestContext(req);
       String dirPath=getServletContext().getRealPath("/temp");
       File dir = new File(dirPath); //just make temp dir manually before hand
       if(FileUploadBase.isMultipartContent(reqContext)){
          FileItemFactory factory = new DiskFileItemFactory();
          ServletFileUpload upload = new ServletFileUpload(factory);
          try{
               List  items = upload.parseRequest(reqContext);
               FileItem item = (FileItem) items.get(0);
               String clientName = item.getName();
               File file = File.createTempFile("upload",
                                               clientName.substring(clientName.lastIndexOf(".")) ,
                                               dir);
               item.write(file);
               out.println("<html>");
               out.println("<head><title>File Upload</title></head>");
               out.println("<body>");
               out.println("Your file was uploaded to " + file.getName());
               out.println("</body></html>");
          }catch(Exception e){
               System.out.println("error"+e.getMessage());
               e.printStackTrace();
          }
       } else{  
               out.println("<html>");
               out.println("<head><title>Uploading Error</title></head>");
               out.println("<body>");
               out.println("Problem at server.");
               out.println("</body></html>");
             }
     }
}
Avatar of leogc

ASKER

I tried using this program.If i use this program i dodnt have control over the filename after uploading.I want to rename the file as uploadedfilename1,uploadedfilename2.how to do this.
one more thing i dodnt want to upload files which are more than 2 mb files.so i tried the following code:
DiskFileItemFactory factory = new DiskFileItemFactory();
          factory.setSizeThreshold(2000);

but still it is uploading the file more than 2mb. once the file size exceeds 2mb size
i want to display a message "file size with more than 2mb cannot be uploaded".How to do this.
regards
leo
>I want to rename the file as uploadedfilename1,uploadedfilename2.    
If we assume that dirPath points to the directory that you are putting the files then
 File dir = new File(dirPath);
 int number = dir.list().length; // assuming that dir only contains the uploaded files.
 // then down in try block you could use
               File file = new File("uploadedfilename" + number +
                                               clientName.substring(clientName.lastIndexOf(".") -1) ,
                                               dir);

>i want to display a message "file size with more than 2mb cannot be uploaded".      
you could use  
if(item.getSize() > 2000000){  }
but it might be easier to change  
if(FileUploadBase.isMultipartContent(reqContext)){
to
if(FileUploadBase.isMultipartContent(reqContext) && reqContext.getContentLength() < 2000000){
see
http://jakarta.apache.org/commons/fileupload/apidocs/org/apache/commons/fileupload/RequestContext.html 
I didn't have time to test. Post your code if you have a problem.   rrz


Avatar of leogc

ASKER

File file = new File("uploadedfilename" + number +
                                               clientName.substring(clientName.lastIndexOf(".") -1) ,
                                               dir);
the above code is causing compilation problem.

cannot resolve symbol
  [javac] symbol  : constructor File (java.lang.String,java.io.File)
  [javac] location: class java.io.File
  [javac]                 File file = new File("uploadedfilename" + number + +clientName.substring(clientName.lastIndexOf(".") -1),dir);
 
My mistake, I put the parameters in the wrong order. See  
http://java.sun.com/j2se/1.5.0/docs/api/java/io/File.html   
and try  
 File file = new File( dir,
                              "uploadedfilename" + number +
                               clientName.substring(clientName.lastIndexOf(".") -1) );  
I hope your learning something.    rrz
Avatar of leogc

ASKER

The above code is not renaming the file in the expected format.For example if i have a file named link.txt,i want to rename the file as link1.txt but the above code is renaming as uploadedfilename1k.txt .
Also reqContext.getContentLength() gives the length of the request.It does not give the size of the uploaded file.If my request contains addtional textfield
values then reqContext.getContentLength() gives the length of request but not the
exact size of uploaded file.In this case how to check for the uploaded file size.Any suggestions on this will be helpful.
Regards
leo
I had some to test this one. I hope your happy.  rrz  

import java.io.*;
import java.util.*;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.*;
import org.apache.commons.fileupload.servlet.*;
public class leogc2 extends HttpServlet
{
     public void doPost(HttpServletRequest req,HttpServletResponse res)throws
     ServletException,IOException
     {          
       res.setContentType("text/html");
       PrintWriter out = res.getWriter();
       RequestContext reqContext = new ServletRequestContext(req);
       String dirPath = getServletContext().getRealPath("/temp");
       File dir = new File(dirPath); //just make temp dir manually before hand
       int number = dir.list().length;
       if(FileUploadBase.isMultipartContent(reqContext)){
          FileItemFactory factory = new DiskFileItemFactory();
          ServletFileUpload upload = new ServletFileUpload(factory);
          try{
               out.println("<html>");
               out.println("<head><title>File Upload</title></head>");
               out.println("<body>");
               List  items = upload.parseRequest(reqContext);
               FileItem item = (FileItem) items.get(0);
               if(item.getSize() < 2000000){  
                  String fileName = item.getName();
                  int index1 = fileName.lastIndexOf("\\");
                  if(index1 != -1)fileName = fileName.substring(index1 + 1);
                    else{
                      int index2 = fileName.lastIndexOf("/");
                      if(index2 != -1)fileName = fileName.substring(index1 + 1);
                      }
                  int index3 = fileName.lastIndexOf(".");
                  if(index3 != -1){
                               fileName = fileName.substring(0,index3) + number
                                                + fileName.substring(index3);
                               File file = new File(dirPath,fileName);
                               item.write(file);
                               out.println("Your file was uploaded to " + file.getName());
                  }else{
                     out.println("No file was not uploaded!");
                    }
               }else out.println("File is too big!");
               out.println("</body></html>");
          }catch(Exception e){
               System.out.println("error"+e.getMessage());
               e.printStackTrace();
          }
       } else{  
               out.println("<html>");
               out.println("<head><title>Uploading Error</title></head>");
               out.println("<body>");
               out.println("Problem at server.");
               out.println("</body></html>");
             }
     }
}
oops lost the first few lines.  

package upload;
import javax.servlet.*;
import javax.servlet.http.*;
import java.io.*;
import java.util.*;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.*;
import org.apache.commons.fileupload.servlet.*;
public class leogc2 extends HttpServlet
{
     public void doPost(HttpServletRequest req,HttpServletResponse res)throws
     ServletException,IOException
     {          
       res.setContentType("text/html");
       PrintWriter out = res.getWriter();
       RequestContext reqContext = new ServletRequestContext(req);
       String dirPath = getServletContext().getRealPath("/temp");
       File dir = new File(dirPath); //just make temp dir manually before hand
       int number = dir.list().length;
       if(FileUploadBase.isMultipartContent(reqContext)){
          FileItemFactory factory = new DiskFileItemFactory();
          ServletFileUpload upload = new ServletFileUpload(factory);
          try{
               out.println("<html>");
               out.println("<head><title>File Upload</title></head>");
               out.println("<body>");
               List  items = upload.parseRequest(reqContext);
               FileItem item = (FileItem) items.get(0);
               if(item.getSize() < 2000000){  
                  String fileName = item.getName();
                  int index1 = fileName.lastIndexOf("\\");
                  if(index1 != -1)fileName = fileName.substring(index1 + 1);
                    else{
                      int index2 = fileName.lastIndexOf("/");
                      if(index2 != -1)fileName = fileName.substring(index1 + 1);
                      }
                  int index3 = fileName.lastIndexOf(".");
                  if(index3 != -1){
                               fileName = fileName.substring(0,index3) + number
                                                + fileName.substring(index3);
                               File file = new File(dirPath,fileName);
                               item.write(file);
                               out.println("Your file was uploaded to " + file.getName());
                  }else{
                     out.println("No file was not uploaded!");
                    }
               }else out.println("File is too big!");
               out.println("</body></html>");
          }catch(Exception e){
               System.out.println("error"+e.getMessage());
               e.printStackTrace();
          }
       } else{  
               out.println("<html>");
               out.println("<head><title>Uploading Error</title></head>");
               out.println("<body>");
               out.println("Problem at server.");
               out.println("</body></html>");
             }
     }
}
Avatar of leogc

ASKER

If i place two textfields in my jsp and try to run the above servlet it is throwing
NullPointer exception.My jsp looks like this
<html>
<head>
<script>
     function uploadfile()
      {
         
          form=document.forms[0];
          form.action="/fileupload/upload";
                     form.submit();
      }
</script>
</head>
<body>
<form method="post" enctype="multipart/form-data">
Name:&nbsp;<input type="text" name="name"><br>
Email:&nbsp;<input type="text" name="email"><br>
<font color="blue" size="5">Attach Files</font><br>
Click "Browse" to select a file.You can attach files up to a<br>
total message size of 2.0MB.<br>
File 1:<input type="file" name="file1"/><br>
<input type="button" value="Attach Files" onclick="uploadfile()"/>
</form>
</body>
</html>
package upload;
import javax.servlet.*;
import javax.servlet.http.*;
import java.io.*;
import java.util.*;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.*;
import org.apache.commons.fileupload.servlet.*;
public class leogc3 extends HttpServlet
{
     public void doPost(HttpServletRequest req,HttpServletResponse res)throws
     ServletException,IOException
     {          
       res.setContentType("text/html");
       PrintWriter out = res.getWriter();
       out.println("<html>");
       out.println("<head><title>File Upload</title></head>");
       out.println("<body>");
       RequestContext reqContext = new ServletRequestContext(req);
       String dirPath = getServletContext().getRealPath("/temp");
       File dir = new File(dirPath); //just make temp dir manually before hand
       int number = dir.list().length;
       if(FileUploadBase.isMultipartContent(reqContext)){
          FileItemFactory factory = new DiskFileItemFactory();
          ServletFileUpload upload = new ServletFileUpload(factory);
          List  items = null;
          try{
               items = upload.parseRequest(reqContext);
             } catch(FileUploadException fue){throw new ServletException(fue);}  
          FileItem item = null;
          for (int i = 0; i < items.size(); i ++) {
             item = (FileItem) items.get(i);
             if(item.isFormField()){
                                    String fieldName = item.getFieldName();
                                    if("name".equals(fieldName)){
                                             out.println("name=" + item.getString());
                                    }
                                    if("email".equals(fieldName)){
                                             out.println("email=" + item.getString());
                                    }
             }else{
                   if(item.getSize() < 2000000){  
                      String fileName = item.getName();
                      int index1 = fileName.lastIndexOf("\\");
                      if(index1 != -1)fileName = fileName.substring(index1 + 1);
                        else{
                             int index2 = fileName.lastIndexOf("/");
                             if(index2 != -1)fileName = fileName.substring(index1 + 1);
                            }
                      int index3 = fileName.lastIndexOf(".");
                      if(index3 != -1){
                              fileName = fileName.substring(0,index3) + number
                                                + fileName.substring(index3);
                              File file = new File(dirPath,fileName);
                              try{
                                  item.write(file);
                                 }catch(Exception e){throw new ServletException(e);}
                              out.println("Your file was uploaded to " + file.getName());
                      }else out.println("No file was not uploaded!");
                   }else out.println("File is too big!");
                }
          }
       }else{  
             out.println("Problem with upload!");
            }
       out.println("</body></html>");
     }
}
Avatar of leogc

ASKER

The fileupload part is working correctly now.Thanks for the reply.Now i want to store the original file path and the renamed file path in database so that it can be
retrieved later.Any inputs of how to do this will be helpful.
regards
leo
ASKER CERTIFIED SOLUTION
Avatar of rrz
rrz
Flag of United States of America image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial