18 December 2009

file upload using servlet

Hi friends
Here is the example to upload a file using java servlet technology.

<table>
<tbody>
<tr>
<form action="http://your_host/servlet/UploadServlet?your_config" enctype="multipart/form-data" method="post">

<td> <input name="fname" size="20" type="file" /> </td>
<td> <input type="Submit" value="Upload" /> </td> </form>

</tr>

</tbody></table>


import java.io.File;
import java.io.IOException;
import java.util.Iterator;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.fileupload.DiskFileUpload;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileItemFactory;
import org.apache.commons.fileupload.FileUpload;
import org.apache.commons.fileupload.FileUploadException;



public class UploadFile extends HttpServlet {

public void doPost(HttpServletRequest req HttpServletResponse res)
{
try{

FileUpload fup new FileUpload();
boolean isMultipart FileUpload.isMultipartContent(req);
// Create a new file upload handler
System.out.println(isMultipart);
DiskFileUpload upload new DiskFileUpload();

// Parse the request
List /* FileItem */ items upload.parseRequest(req);

Iterator iter items.iterator();
while (iter.hasNext()) {

FileItem item (FileItem) iter.next();

if (item.isFormField()) {
System.out.println( its a field );
} else {
System.out.println( its a file );
System.out.println(item.getName());
File cfile new File(item.getName());
File tosave new File(getServletContext().getRealPath( / ) cfile.getName());
item.write(tosave);
}
}

}catch(Exception e){System.out.println(e);}
}
}

describe servlet in your web.xml file: 

<servlet>
    
<servlet-name>UploadServlet</servlet-name>
    
<servlet-class>com.jsos.upload.UploadServlet</servlet-class>
<init-param>
     
<param-name>config</param-name>
     
<param-value>path_to_your_configuration_file</param-value>
    
</init-param>
</servlet>

<servlet-mapping>
 
<servlet-name>UploadServlet</servlet-name>
 
<url-pattern>/servlet/UploadServlet</url-pattern>
</servlet-mapping>

  • Servlet's configuration file can be saved anywhere on your server. i.e. if you are using UploadServlet?config line we assume this file is saved under the root directory of  your servletrunner. 
  • You can use query string for servlet in this form too: 
    UploadServlet?config=your_config_file&name=file_name. 
    This way you can provide a name for the uploaded file right in the query string. This option could be useful if you are generating upload forms (pages) dynamically.

 

1 comment:

  1. hi i cant able to run this servlet code in netbeans6.9 if you dont mind can you explain me

    thanking you

    ReplyDelete