HomeTagSubmit NotesAsk AnythingLoginSubscribe Us
1. Feel Free to ask and submit anything on and get satisfactory answer
2. Registration is not compulsory, you can directly login via google or facebook
3. Our Experts are looking for yours ?.

java-servlet: How to upload file on server ?

I want to upload file on server in a folder under root directory. Please give me source code of uploading file using servlet.

java x 211
servlet x 20
Posted On : 2013-12-01 19:49:32.0
profile Garima Gupta - Garima Gupta


For uploading a file to the server, method must be post and enctype must be multipart/form-data in html file.

********************** Example of uploading file to the server in servlet **********************

index.html :
<form action="go" method="post" enctype="multipart/form-data">
Select File:<input type="file" name="fname"/><br/>
<input type="submit" value="upload"/>

Now, for uploading a file to the server, there can be various ways. But, I am going to use MultipartRequest class provided by oreilly. For using this class you must have cos.jar file. :
import javax.servlet.ServletException;
import javax.servlet.http.*;
import com.oreilly.servlet.MultipartRequest;

public class UploadServlet extends HttpServlet {

public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {

PrintWriter out = response.getWriter();

MultipartRequest m=new MultipartRequest(request,"d:/new");
out.print("successfully uploaded");

There are two arguments passed in MultipartRequest class constructor, first one is HttpServletRequest object and second one is String object (for location). Here I am supposing that you have new folder in D drive.
web.xml :
This configuration file provides information about the servlet.





As in above example we are considering that the file should go in D drive in new folder. If you want to upload file in a folder under root directory, you can get the root folder path using :
String path= request.getSession().getServletContext().getRealPath("/").concat("Name of the folder in root");
now use MultipartRequest m=new MultipartRequest(request,path);

Posted On : 2013-12-01 20:16:34
Satisfied : 2 Yes  0 No
profile Rishi Kumar - Rishi Kumar
Reply This Thread

Post Answer
Please Login First to Post Answer: Login login with facebook -