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 :
-----------------
<html>
<body>
<form action="go" method="post" enctype="multipart/form-data">
Select File:<input type="file" name="fname"/><br/>
<input type="submit" value="upload"/>
</form>
</body>
</html>
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.
UploadServlet.java :
-----------------------------
import java.io.*;
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 {
response.setContentType("text/html");
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.
<web-app>
<servlet>
<servlet-name>UploadServlet</servlet-name>
<servlet-class>UploadServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>UploadServlet</servlet-name>
<url-pattern>/go</url-pattern>
</servlet-mapping>
</web-app>
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);
3