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:
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>JavaWithBreakfast</title>
<style>
p {
border: 1px solid grey;
padding: 10px;
margin: 30px;
}
</style>
</head>
<body>
<form action="myUpload" method="post" enctype="multipart/form-data">
<p>
<input type="file" name="file" />
<input type="submit" value="click here to upload"/>
</p>
</form>
</body>
</html>
view raw uploadPage.jsp hosted with ❤ by GitHub


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


package test;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import javax.servlet.ServletException;
import javax.servlet.annotation.MultipartConfig;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.Part;
/**
* Servlet implementation class UploadServlet
*/
@WebServlet("/myUpload")
@MultipartConfig
public class UploadServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
/**
* @see HttpServlet#HttpServlet()
*/
public UploadServlet() {
super();
// TODO Auto-generated constructor stub
}
/**
* @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse
* response)
*/
protected void doGet(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
}
/**
* @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
* response)
*/
protected void doPost(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
Part filePart = request.getPart("file");
// obtain file name from header
String content = filePart.getHeader("content-disposition");
String filename = "";
for (String token : content.split(";")) {
if (token.trim().startsWith("filename")) {
System.out.println(token);
filename = token.substring(token.indexOf("=") + 2,
token.length() - 1);
System.out.println(filename);
}
}
// path where the file will be placed:
String path = "C:\\uploads";
System.out.println(path);
// obtain file content
InputStream fileContent = filePart.getInputStream();
OutputStream out = new FileOutputStream(new File(path + File.separator
+ filename));
int read = 0;
final byte[] bytes = new byte[1024];
while ((read = fileContent.read(bytes)) != -1) {
out.write(bytes, 0, read);
}
}
}

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