Tuesday, 4 December 2012

File Uploading through Servlet

Posted by Naveen Katiyar On 02:37 No comments
Steps to upload a file:-

1.Specify the request method POST.
2.Add the enctype attribute of form tag.ie.
<form action="test.htm" method="post" enctype="multipart/form-data"/>
3.use the <input type="file"/>
4.use the third party vendor specific class to upload the files at server side.
NOTE:cos.jar file contains a class MultipartRequest and this class is responsible to upload the files at server side.This class is defined in com.oreilly.servlet package.

If you dont want to use any third party jar then switch to servlet 3.0.

code of index.jsp:-

<html>
<body bgcolor="yellow">
<form action="test.htm" method="post" enctype="multipart/form-data">
enter name:<input type="text" name="textname"><br>
select file:<input type="file" name="file"><br>
<input type="submit" value="submit">
</form>
</body>
</html>

code of UploadServlet:-

import javax.servlet.*;
import javax.servlet.http.*;
import java.io.*;
import com.oreilly.servlet.*;
public class UploadServlet extends HttpServlet
{
public void doPost(HttpServletRequest request,HttpServletResponse response)
throws ServletException,IOException
{
try
{
response.setContentType("text/html");
PrintWriter out=response.getWriter();
out.println("<html><body bgcolor=yellow>");
String n=request.getParameter("textname");
out.println("userid:"+n);
String p=this.getServletConfig().getServletContext().getRealPath("");
p=p+"\\"+"upload";
MultipartRequest multi=new MultipartRequest(request,p,10*1024*1024);
String fn=multi.getOriginalFileName("file");
String id=multi.getParameter("textname");
out.println("userid:"+id);
out.println(fn+"file is uploaded");
out.println("</body></html>");
out.close();
}catch(Exception e){System.out.println(e);}
}
}

upload is the folder where file will be uploaded and is located parallel to WEB-INF.
*Note:-Request object is set to null after uploading.so,you should use multipart object to get the request parameters..

Click here to get working example

0 comments: