Servlet File Uploading - Following is an example which describes more about the file uploading by using servlet concept.
UploadServlet.java
[java]package fileupload;
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,"E:/sai");
out.print("Hey man file has been successfully uploaded");
}
} [/java]
The
form() method attribute ought to be set to POST method and GET method can not be used. The form enctype credit ought to be set to multipart/structure data. The form action attribute ought to be set to a servlet record which would handle document transferring at backend server. The doPost() shall be used when comparatively large amount of sensitive data has to be sent. Examples are sending data after filling up a form or sending login id and password.
Sets the content type of the response being sent to the client, if the response has not been committed yet. The given content type may include a character encoding specification.
index.html
[html]<html>
<body style="background:#80BFFF">
<form action="./go" method="post" enctype="multipart/form-data">
<center><h1>SPlessons File uploading Application</h1></center>
<center>Select File:<input type="file" name="fname"/><br/> </br>
<input type="submit" value="upload"/> </center>
</form>
</body>
</html> [/html]
Here the developer just created a text box to select the file and created a upload button to upload the file. make sure that this URL should be match with servlet URL.
web.xml
[xml]<web-app>
<servlet>
<servlet-name>UploadServlet</servlet-name>
<servlet-class>fileupload.UploadServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>UploadServlet</servlet-name>
<url-pattern>/go</url-pattern>
</servlet-mapping>
</web-app> [/xml]
Maku sure that servlet name should be same and URL should be match with
HTML form.
Output
Following is the page will be displayed when compile the program. Here user can select files from the System, the selected file will be placed in a particular destination.
File will be uploaded to the given folder and message will be as follows.