Sunday 13 March 2016

How to upload files using Servlet technology

This time, the aim of this post is to describe how to upload files to a server using servlet technology.

Upload files with Java technology is easy, we only need to create a JSP page and a servlet class, but we have to take into account this form will be a bit different than usual:
  • Method POST 
  • multipart/form-data 

Form declaration in the JSP:
<form action="upload" method="post" enctype="multipart/form-data">

Annotations in the servlet declaration:
@WebServlet("/UploadServlet")
@MultipartConfig
public class UploadServlet extends HttpServlet {

JSP code:


Servlet code:
* This example project is using servlet library version 3.0 or above.



Method post - summary:

1) Getting the file attribute from the request object. file attribute corresponds
with the name of the input type ="file" in the JSP. The object obtained is Part type.

2) Obtain the name of the file uploaded:
using filePart.getHeader to obtain the value of the property filename.

3) Defining an object OutputStream with the destination path, plus the file name).

4) Read the content of the object filepart obtained in point 1, and writing the bytes into the ouputStream (in the destination).


Running the application:  
http://localhost:8080/UploadWeb/

 Select a file from the local disk and click the button to submit the request:

The server logs will display this message:
INFO: Reloading Context with name [/UploadWeb] is completed

Checking the execution result (the path selected in the example is also a local directory C:/uploads), we can verify the file has been uploaded successfully to the selected destination.



No comments:

Post a Comment