Upload file using Java

The code below shows the way to upload a file using jsp and read the form data

File 1: index.jsp


<form action="upload.jsp" method="post" enctype="multipart/form-data"

name="form" id="form" >

   <table width="auto" align="center"  cellpadding="2" cellspacing="2">

<tr class="normal">
           <td width="auto" align="center" class="normal">
           <b> Name : </b></td>
           <td>
           <input name="name" type="name"  class="normal"  style="color: fuchsia; "  >    
     </td>    
     </tr>

     <tr class="normal">
           <td width="auto" align="center" class="normal">
           <b> File Name : </b></td>
           <td>
           <input name="file" type="file"  class="normal"  style="color: fuchsia; "  >    
     </td>    
     </tr>
   
         <tr height="35" >
         <td  colspan="2" >
         <center>
         <INPUT TYPE="SUBMIT" class="button" VALUE="Upload">
         </center>
         </td>
         </tr>
         </table>




File 2: upload.jsp



<%

    boolean isMultipart = FileUpload.isMultipartContent(request);

    DiskFileUpload upload = new DiskFileUpload();
   
    String fname="";
    // First parse this request by the handler.This gives us a list of items from the request
   
    List items = upload.parseRequest(request);
    Iterator itr = items.iterator();
   
   
    try{
   
    seqname=randomString(8);       
   
    while(itr.hasNext()) {
   
    FileItem item = (FileItem) itr.next();
       
    // check if the current item is a form field or an uploaded file
    if(item.isFormField()) {
           
    // get the name of the field
    String fieldName = item.getFieldName();
   
    // if it is name, we can set it in request to thank the user
    if(fieldName.equals("name"))
        System.out.println(item.getString());

    } else {

        // the item must be an uploaded file save it to disk. Note that there
        // seems to be a bug in item.getName() as it returns the full path on
        // the client's machine for the uploaded file name, instead of the file
        // name only. To overcome that, I have used a workaround using
        // fullFile.getName().
        File fullFile  = new File(item.getName()); 
                fname=fullFile.getName();
              
                fname=fname.substring((fname.lastIndexOf("."))+1);
               
               if("xls".equals(fname))
                {  
                fname=seqname+"."+fname;
            
        File savedFile = new File(getServletContext().getRealPath("/")+"/uploads",fname);
       
        item.write(savedFile);
       
              
                }
%>

No comments:

Post a Comment