How to Read an External File From Servletcontext

Servlet Upload File and Download File is a common chore in java web application. Since I have written a lot about coffee servlet recently, I idea to provide a sample example of servlet file upload to server then download from server to client.

Servlet Upload File

Our use example is to provide a unproblematic HTML page where client can select a local file to be uploaded to server. On submission of request to upload the file, our servlet program will upload the file into a directory in the server and so provide the URL through which user can download the file. For security reason, user will not be provided direct URL for downloading the file, rather they will be given a link to download the file and our servlet will process the asking and send the file to user.

Nosotros will create a dynamic web project in Eclipse and the project structure will expect similar below image.

Servlet Upload File, java upload file to server, servlet download file

Let'south look into all the components of our spider web application and understand the implementation.

HTML Page for Java Uploading File to Server

We tin can upload a file to server by sending a mail service request to servlet and submitting the form. Nosotros can't employ Get method for uploading file.

Some other point to note is that enctype of course should be multipart/form-data.

To select a file from user file organization, we need to utilise input element with blazon as file.

So we can have a elementary HTML page index.html for uploading file equally:

                          <html> <head></head> <body> <form action="UploadDownloadFileServlet" method="post" enctype="multipart/class-data"> Select File to Upload:<input type="file" name="fileName"> <br> <input type="submit" value="Upload"> </form> </body> </html>                      

Server File Location for File Upload

Nosotros need to store file into some directory at server, we can have this directory hardcoded in plan just for better flexibility, we will go along it configurable in deployment descriptor context params. Likewise we will add our upload file html page to the welcome file list.

Our web.xml file volition look similar below:

                          <?xml version="1.0" encoding="UTF-viii"?> <web-app xmlns:xsi="https://world wide web.w3.org/2001/XMLSchema-instance" xmlns="https://coffee.sun.com/xml/ns/javaee" xsi:schemaLocation="https://coffee.sun.com/xml/ns/javaee https://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" version="3.0">   <display-name>ServletFileUploadDownloadExample</brandish-name>   <welcome-file-list>     <welcome-file>index.html</welcome-file>   </welcome-file-listing>   <context-param>     <param-name>tempfile.dir</param-proper noun>     <param-value>tmpfiles</param-value>   </context-param> </web-app>                      

ServletContextListener for File Upload Location

Since we need to read context parameter for file location and create a File object from it, we can write a ServletContextListener to do it when context is initialized. We can set up absolute directory location and File object as context attribute to exist used past other servlets.

Our ServletContextListener implementation code is similar below.

                          package com.journaldev.servlet;  import coffee.io.File;  import javax.servlet.ServletContext; import javax.servlet.ServletContextEvent; import javax.servlet.ServletContextListener; import javax.servlet.annotation.WebListener;  @WebListener public form FileLocationContextListener implements ServletContextListener {      public void contextInitialized(ServletContextEvent servletContextEvent) {     	String rootPath = System.getProperty("catalina.domicile");     	ServletContext ctx = servletContextEvent.getServletContext();     	String relativePath = ctx.getInitParameter("tempfile.dir");     	File file = new File(rootPath + File.separator + relativePath);     	if(!file.exists()) file.mkdirs();     	Organisation.out.println("File Directory created to be used for storing files");     	ctx.setAttribute("FILES_DIR_FILE", file);     	ctx.setAttribute("FILES_DIR", rootPath + File.separator + relativePath);     }  	public void contextDestroyed(ServletContextEvent servletContextEvent) { 		//exercise cleanup if needed 	} 	 }                      

File Upload Download Servlet

Update: Servlet Specs 3 added back up to upload files on server in the API, so we won't need to utilize any tertiary party API. Delight cheque out Servlet 3 Upload File.

For File upload, we will employ Apache Eatables FileUpload utility, for our projection we are using version 1.3, FileUpload depends on Apache Commons IO jar, and so we need to place both in the lib directory of the project, as you tin see that in to a higher place image for project construction.

We will use DiskFileItemFactory factory that provides a method to parse the HttpServletRequest object and return list of FileItem. FileItem provides useful method to get the file proper noun, field name in form, size and content type details of the file that needs to be uploaded. To write file to a directory, all we need to do information technology create a File object and pass it as argument to FileItem write() method.

Since the whole purpose of the servlet is to upload file, we will override init() method to initialise the DiskFileItemFactory object instance of the servlet. We will use this object in the doPost() method implementation to upload file to server directory.

Once the file gets uploaded successfully, we will send response to client with URL to download the file, since HTML links use Get method,nosotros will append the parameter for file name in the URL and we can utilise the same servlet doGet() method to implement file download process.

For implementing download file servlet, first we will open the InputStream for the file and employ ServletContext.getMimeType() method to get the MIME type of the file and set it as response content type.

We will as well need to set the response content length as length of the file. To brand sure that client understand that we are sending file in response, nosotros need to set up "Content-Disposition" header with value equally "attachment; filename="fileName".

Once nosotros are done with setting response configuration, we can read file content from InputStream and write it to ServletOutputStream and the flush the output to client.

Our final implementation of UploadDownloadFileServlet servlet looks like below.

                          package com.journaldev.servlet;  import java.io.File; import coffee.io.FileInputStream; import java.io.IOException; import java.io.InputStream; import java.io.PrintWriter; import java.util.Iterator; import coffee.util.Listing;  import javax.servlet.ServletContext; import javax.servlet.ServletException; import javax.servlet.ServletOutputStream; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse;  import org.apache.commons.fileupload.FileItem; import org.apache.commons.fileupload.FileUploadException; import org.apache.commons.fileupload.disk.DiskFileItemFactory; import org.apache.commons.fileupload.servlet.ServletFileUpload;  @WebServlet("/UploadDownloadFileServlet") public class UploadDownloadFileServlet extends HttpServlet { 	individual static terminal long serialVersionUID = 1L;     private ServletFileUpload uploader = null; 	@Override 	public void init() throws ServletException{ 		DiskFileItemFactory fileFactory = new DiskFileItemFactory(); 		File filesDir = (File) getServletContext().getAttribute("FILES_DIR_FILE"); 		fileFactory.setRepository(filesDir); 		this.uploader = new ServletFileUpload(fileFactory); 	} 	protected void doGet(HttpServletRequest asking, HttpServletResponse response) throws ServletException, IOException { 		String fileName = request.getParameter("fileName"); 		if(fileName == null || fileName.equals("")){ 			throw new ServletException("File Name tin can't be aught or empty"); 		} 		File file = new File(asking.getServletContext().getAttribute("FILES_DIR")+File.separator+fileName); 		if(!file.exists()){ 			throw new ServletException("File doesn't exists on server."); 		} 		System.out.println("File location on server::"+file.getAbsolutePath()); 		ServletContext ctx = getServletContext(); 		InputStream fis = new FileInputStream(file); 		String mimeType = ctx.getMimeType(file.getAbsolutePath()); 		response.setContentType(mimeType != naught? mimeType:"awarding/octet-stream"); 		response.setContentLength((int) file.length()); 		response.setHeader("Content-Disposition", "attachment; filename=\"" + fileName + "\""); 		 		ServletOutputStream bone = response.getOutputStream(); 		byte[] bufferData = new byte[1024]; 		int read=0; 		while((read = fis.read(bufferData))!= -1){ 			bone.write(bufferData, 0, read); 		} 		os.flush(); 		os.close(); 		fis.close(); 		Organisation.out.println("File downloaded at client successfully"); 	}  	protected void doPost(HttpServletRequest asking, HttpServletResponse response) throws ServletException, IOException { 		if(!ServletFileUpload.isMultipartContent(request)){ 			throw new ServletException("Content type is not multipart/class-data"); 		} 		 		response.setContentType("text/html"); 		PrintWriter out = response.getWriter(); 		out.write("<html><head></caput><trunk>"); 		try { 			List<FileItem> fileItemsList = uploader.parseRequest(request); 			Iterator<FileItem> fileItemsIterator = fileItemsList.iterator(); 			while(fileItemsIterator.hasNext()){ 				FileItem fileItem = fileItemsIterator.side by side(); 				System.out.println("FieldName="+fileItem.getFieldName()); 				Arrangement.out.println("FileName="+fileItem.getName()); 				System.out.println("ContentType="+fileItem.getContentType()); 				System.out.println("Size in bytes="+fileItem.getSize()); 				 				File file = new File(request.getServletContext().getAttribute("FILES_DIR")+File.separator+fileItem.getName()); 				Organization.out.println("Absolute Path at server="+file.getAbsolutePath()); 				fileItem.write(file); 				out.write("File "+fileItem.getName()+ " uploaded successfully."); 				out.write("<br>"); 				out.write("<a href=\"UploadDownloadFileServlet?fileName="+fileItem.getName()+"\">Download "+fileItem.getName()+"</a>"); 			} 		} catch (FileUploadException e) { 			out.write("Exception in uploading file."); 		} catch (Exception eastward) { 			out.write("Exception in uploading file."); 		} 		out.write("</body></html>"); 	}  }                      

The sample execution of the projection is shown in below images.

Servlet File Upload HTML JSP Form

Servlet File Upload to Server

Servlet Download File

Download Servlet File Upload Download Projection

You can download Apache Commons IO jar and Apache Commons FileUpload jar from below URLs.

https://commons.apache.org/proper/eatables-fileupload/download_fileupload.cgi
https://commons.apache.org/proper/commons-io/download_io.cgi

Cheque out next commodity in the series well-nigh Servlet Exception Handling.

How to Read an External File From Servletcontext

Source: https://www.journaldev.com/1964/servlet-upload-file-download-example

0 Response to "How to Read an External File From Servletcontext"

Post a Comment

Iklan Atas Artikel

Iklan Tengah Artikel 1

Iklan Tengah Artikel 2

Iklan Bawah Artikel