Servlet Upload File and Download File Example

Filed Under: Java EE

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

Servlet Upload File

Our use case is to provide a simple 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 then 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 request and send the file to user.

We will create a dynamic web project in Eclipse and the project structure will look like below image.

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

Let’s look into all the components of our web application and understand the implementation.

HTML Page for Java Uploading File to Server

We can upload a file to server by sending a post request to servlet and submitting the form. We can’t use GET method for uploading file.

Another point to note is that enctype of form should be multipart/form-data.

To select a file from user file system, we need to use input element with type as file.

So we can have a simple HTML page index.html for uploading file as:


<html>
<head></head>
<body>
<form action="UploadDownloadFileServlet" method="post" enctype="multipart/form-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

We need to store file into some directory at server, we can have this directory hardcoded in program but for better flexibility, we will keep it configurable in deployment descriptor context params. Also we will add our upload file html page to the welcome file list.

Our web.xml file will look like below:


<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" version="3.0">
  <display-name>ServletFileUploadDownloadExample</display-name>
  <welcome-file-list>
    <welcome-file>index.html</welcome-file>
  </welcome-file-list>
  <context-param>
    <param-name>tempfile.dir</param-name>
    <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 absolute directory location and File object as context attribute to be used by other servlets.

Our ServletContextListener implementation code is like below.


package com.journaldev.servlet;

import java.io.File;

import javax.servlet.ServletContext;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
import javax.servlet.annotation.WebListener;

@WebListener
public class FileLocationContextListener implements ServletContextListener {

    public void contextInitialized(ServletContextEvent servletContextEvent) {
    	String rootPath = System.getProperty("catalina.home");
    	ServletContext ctx = servletContextEvent.getServletContext();
    	String relativePath = ctx.getInitParameter("tempfile.dir");
    	File file = new File(rootPath + File.separator + relativePath);
    	if(!file.exists()) file.mkdirs();
    	System.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) {
		//do cleanup if needed
	}
	
}

File Upload Download Servlet

Update: Servlet Specs 3 added support to upload files on server in the API, so we won’t need to use any third party API. Please check out Servlet 3 Upload File.

For File upload, we will use Apache Commons FileUpload utility, for our project we are using version 1.3, FileUpload depends on Apache Commons IO jar, so we need to place both in the lib directory of the project, as you can see that in above image for project structure.

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 name, 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 it 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,we 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 use ServletContext.getMimeType() method to get the MIME type of the file and set it as response content type.

We will also need to set the response content length as length of the file. To make sure that client understand that we are sending file in response, we need to set “Content-Disposition” header with value as “attachment; filename=”fileName”.

Once we 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 java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.util.Iterator;
import java.util.List;

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 {
	private static final 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 request, HttpServletResponse response) throws ServletException, IOException {
		String fileName = request.getParameter("fileName");
		if(fileName == null || fileName.equals("")){
			throw new ServletException("File Name can't be null or empty");
		}
		File file = new File(request.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 != null? mimeType:"application/octet-stream");
		response.setContentLength((int) file.length());
		response.setHeader("Content-Disposition", "attachment; filename=\"" + fileName + "\"");
		
		ServletOutputStream os = response.getOutputStream();
		byte[] bufferData = new byte[1024];
		int read=0;
		while((read = fis.read(bufferData))!= -1){
			os.write(bufferData, 0, read);
		}
		os.flush();
		os.close();
		fis.close();
		System.out.println("File downloaded at client successfully");
	}

	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		if(!ServletFileUpload.isMultipartContent(request)){
			throw new ServletException("Content type is not multipart/form-data");
		}
		
		response.setContentType("text/html");
		PrintWriter out = response.getWriter();
		out.write("<html><head></head><body>");
		try {
			List<FileItem> fileItemsList = uploader.parseRequest(request);
			Iterator<FileItem> fileItemsIterator = fileItemsList.iterator();
			while(fileItemsIterator.hasNext()){
				FileItem fileItem = fileItemsIterator.next();
				System.out.println("FieldName="+fileItem.getFieldName());
				System.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());
				System.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 e) {
			out.write("Exception in uploading file.");
		}
		out.write("</body></html>");
	}

}

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

Servlet File Upload HTML JSP Form

Servlet File Upload to Server

Servlet Download File

Download Servlet File Upload Download Project

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

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

Check out next article in the series about Servlet Exception Handling.

Comments

  1. Npac says:

    Thank you so much. It helps me lots for my final year project.

  2. Mohammed Akbar says:

    After uploading a file, my servlet page UploadDownloadFileServlet doesn’t print anything as the file uploaded… it’s empty…….

  3. dinesh says:

    Thanks for this tutorial,but when i upload the file it shows Exception in uploading file..can u give any suggestions

  4. Sergey_Zimovets says:

    if you have the exception you should create a file and will be sure that it has utf-8 encoding
    In my case i tryid to upload my old resume file, i had an exception. Then i opened this file in notepad++ and try to change encoding i failed. Then i create simple file with notepad++ and encoding utf-8 and everything workes properly/

  5. Andrey says:

    I had to change a few things to make this work.
    The biggest problem was that fileItem.getName() is a full path to image, not its filename.
    After I added/changed these lines it worked like a charm:

    String fullPath = fileItem.getName();
    String filename = fullPath.substring(fullPath.lastIndexOf(File.separator) + 1);;

    File file = new File(request.getServletContext().getAttribute("FILES_DIR") + File.separator + filename);;

    out.write("UploadDownloadFileServlet?fileName= + filename");

    1. Pitot says:

      Thank you so much, Andrey

  6. anusha jupally says:

    every time i uploading Exception in uploading file.

    1. dinesh says:

      R u solve the error u faced , i am also got the same error

      thanks

  7. Keval Shukla says:

    Please tell me how do i redirect to my targeted page with that file .

  8. Rochelle says:

    Hi Pankaj,

    I tried your code above, it works sometimes, sometimes meaning when I try downloading a 3.3MB zip file it works fine but when I try it on a 3.90 MB it doesn’t work but there are times that it does work. I don’t know if the problem lies on my code or on my server. What do you think?

  9. Gautam says:

    Hi Pankaj,

    I tried your code and it store the file in tmp directory. But i need to store in server. How to save the file in url(server).

    For example my url is www.gautam.com

  10. sakthi says:

    Hi pankaj,
    Plz help me out i am new to java

    Exception in uploading file.

    Absolute Path at server=C:\Users\User pc\Downloads\apache-tomcat-7.0.34\tmpfiles\C:\Users\User pc\Pictures\Screenshots\Screenshot (5).png

  11. Zarue LG says:

    Nice article

  12. Lee Stebbins says:

    Just awesome topic! I recently had to fill out a form and spent an enormous amount of time trying to find an appropriate Just look at the service “http://goo.gl/fy7uke”. Its pretty easy to use. I think you can get a free trial if you ask for it.

  13. aashish says:

    exception in uploading file is the message that keeps on appearing again and again.can’t find the right cause,please help me with this.

  14. Abrar Khan says:

    We also include in web.xml file this line

    com.journaldev.servlet.FileLocationContextListener

    </listener

    otherwise how server will find which is your Listener Class
    its really nice work Thanks Pankaj

    1. Abrar Khan says:

      I am writing here proper but i dont know why it is not coming what i am writing

      inside web.xml give also listener class entry
      “”
      “”
      com.journaldev.servlet.FileLocationContextListener
      “”
      “”

    2. Pankaj says:

      Notice the WebListener annotation.

  15. john Arnedo says:

    Very nice post! thank for you input!

  16. Pankaj says:

    Hey Pankaj, I am getting the below exception. Could You Please Sort it out

    java.io.FileNotFoundException: null\password.txt (The system cannot find the path specified)
    at java.io.FileOutputStream.open(Native Method)
    at java.io.FileOutputStream.(FileOutputStream.java:206)
    at java.io.FileOutputStream.(FileOutputStream.java:156)
    at org.apache.commons.fileupload.disk.DiskFileItem.write(DiskFileItem.java:394)
    at UploadDownloadFileServlet.doPost(UploadDownloadFileServlet.java:148)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:644)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:725)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:301)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
    at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:239)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
    at org.netbeans.modules.web.monitor.server.MonitorFilter.doFilter(MonitorFilter.java:393)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:239)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
    at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:219)
    at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:106)
    at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:503)
    at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:136)
    at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:74)
    at org.apache.catalina.valves.AbstractAccessLogValve.invoke(AbstractAccessLogValve.java:610)
    at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:88)
    at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:516)
    at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1015)
    at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:652)
    at org.apache.coyote.http11.Http11NioProtocol$Http11ConnectionHandler.process(Http11NioProtocol.java:222)
    at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1575)
    at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.run(NioEndpoint.java:1533)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
    at java.lang.Thread.run(Thread.java:745)
    15-Jan-2016 20:46:37.140 INFO [http-nio-8084-exec-406] org.apache.catalina.core.StandardContext.reload Reloading Context with name [/UploadDownload] has started
    15-Jan-2016 20:46:38.650 INFO [http-nio-8084-exec-406] org.apache.jasper.servlet.TldScanner.scanJars At least one JAR was scanned for TLDs yet contained no TLDs. Enable debug logging for this logger for a complete list of JARs that were scanned but no TLDs were found in them. Skipping unneeded JARs during scanning can improve startup time and JSP compilation time.
    15-Jan-2016 20:46:38.664 INFO [http-nio-8084-exec-406] org.apache.catalina.core.StandardContext.reload Reloading Context with name [/UploadDownload] is completed
    15-Jan-2016 20:48:19.393 INFO [http-nio-8084-exec-404] org.apache.catalina.core.StandardContext.reload Reloading Context with name [/UploadDownload] has started
    15-Jan-2016 20:48:20.676 INFO [http-nio-8084-exec-404] org.apache.jasper.servlet.TldScanner.scanJars At least one JAR was scanned for TLDs yet contained no TLDs. Enable debug logging for this logger for a complete list of JARs that were scanned but no TLDs were found in them. Skipping unneeded JARs during scanning can improve startup time and JSP compilation time.
    15-Jan-2016 20:48:20.686 INFO [http-nio-8084-exec-404] org.apache.catalina.core.StandardContext.reload Reloading Context with name [/UploadDownload] is completed
    15-Jan-2016 20:49:40.535 INFO [http-nio-8084-exec-415] org.apache.catalina.core.StandardContext.reload Reloading Context with name [/UploadDownload] has started
    15-Jan-2016 20:49:41.903 INFO [http-nio-8084-exec-415] org.apache.jasper.servlet.TldScanner.scanJars At least one JAR was scanned for TLDs yet contained no TLDs. Enable debug logging for this logger for a complete list of JARs that were scanned but no TLDs were found in them. Skipping unneeded JARs during scanning can improve startup time and JSP compilation time.
    15-Jan-2016 20:49:41.912 INFO [http-nio-8084-exec-415] org.apache.catalina.core.StandardContext.reload Reloading Context with name [/UploadDownload] is completed
    java.io.FileNotFoundException: null\password.txt (The system cannot find the path specified)
    FieldName=fileName
    FileName=password.txt
    ContentType=text/plain
    Size in bytes=10
    Absolute Path at server=C:\Program Files\Apache Software Foundation\Apache Tomcat 8.0.3\bin\null\password.txt
    name=password.txt, StoreLocation=C:\Users\Pankaj\AppData\Roaming\NetBeans\8.0\apache-tomcat-8.0.3.0_base\temp\upload_6dd91dbf_ca99_424f_903f_c21b7763cd48_00000000.tmp, size=10 bytes, isFormField=false, FieldName=fileName
    at java.io.FileOutputStream.open(Native Method)
    at java.io.FileOutputStream.(FileOutputStream.java:206)
    at java.io.FileOutputStream.(FileOutputStream.java:156)
    at org.apache.commons.fileupload.disk.DiskFileItem.write(DiskFileItem.java:394)
    at UploadDownloadFileServlet.doPost(UploadDownloadFileServlet.java:148)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:644)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:725)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:301)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
    at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:239)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
    at org.netbeans.modules.web.monitor.server.MonitorFilter.doFilter(MonitorFilter.java:393)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:239)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
    at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:219)
    at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:106)
    at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:503)
    at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:136)
    at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:74)
    at org.apache.catalina.valves.AbstractAccessLogValve.invoke(AbstractAccessLogValve.java:610)
    at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:88)
    at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:516)
    at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1015)
    at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:652)
    at org.apache.coyote.http11.Http11NioProtocol$Http11ConnectionHandler.process(Http11NioProtocol.java:222)
    at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1575)
    at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.run(NioEndpoint.java:1533)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
    at java.lang.Thread.run(Thread.java:745)

  17. Suneel Kumar says:

    Hi,

    I am getting the following error after upload and submitting the file..

    ===================================================

    type Status report

    message /UploadDownloadFileServlet

    description The requested resource is not available.

    ===================================================

    can u pls help me?

  18. Irshad says:

    Its working fine but want multiple file download then i need to do

    Please help me

  19. Irshad says:

    Hi Pankaj,

    I have uploaded the file successfully but when i click to download the got excep : HTTP Status 404

    description The requested resource is not available.

    Please help me

  20. Swathi says:

    Hi Pankaj

    I am getting below exception in tomcat console

    rg.apache.catalina.LifecycleException: Failed to start component [StandardEngine[Catalina].StandardHost[localhost].StandardContext[/UploadFileServletApp]]
    at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:154)
    at org.apache.catalina.core.ContainerBase.addChildInternal(ContainerBase.java:901)
    at org.apache.catalina.core.ContainerBase.addChild(ContainerBase.java:877)
    at org.apache.catalina.core.StandardHost.addChild(StandardHost.java:618)
    at org.apache.catalina.startup.HostConfig.deployDescriptor(HostConfig.java:650)
    at org.apache.catalina.startup.HostConfig$DeployDescriptor.run(HostConfig.java:1582)
    at java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:471)
    at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:334)
    at java.util.concurrent.FutureTask.run(FutureTask.java:166)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1145)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:615)
    at java.lang.Thread.run(Thread.java:722)
    Caused by: java.lang.NoClassDefFoundError: org/apache/commons/fileupload/FileUploadException

    I have commons-fileupload-1.2.2.jar in my lib

    Can u please let me know how can i resolve this problem

  21. Swathi says:

    Hi

    I am getting below error

    SEVERE: Servlet.service() for servlet [jsp] in context with path [/UploadFileServletApp] threw exception [Unable to compile class for JSP] with root cause
    java.lang.ClassNotFoundException: com.sun.el.ExpressionFactoryImpl
    at org.apache.catalina.loader.WebappClassLoader.loadClass(WebappClassLoader.java:1714)

    Can you please let me know how can i solve this problem

  22. Arpit says:

    Hi Pankaj,

    Your code is working fine but I want to upload file with same name as well as same file type. Please help me in this matter. Thanks in advance.
    For Ex. if I want to Arpit.pdf to server, I am getting some random name and “tmp” file type instead of pdf.

    Regards,
    Arpit

  23. swati ghai says:

    i have studied your program ..it is quite good but please tell me…what should i do?
    my requirement is i need this project but instead of uploading all files it should upload only .txt files..nd if user tries to enter other than this it should throw error

  24. swathi says:

    [INFO] Scanning for projects…
    [INFO] Downloading: http://repo.maven.apache.org/maven2/org/codehaus/mojo/maven-metadata.xml
    [INFO] Downloading: http://repo.maven.apache.org/maven2/org/apache/maven/plugins/maven-metadata.xml
    [INFO] Downloaded: http://repo.maven.apache.org/maven2/org/apache/maven/plugins/maven-metadata.xml (13 KB at 2.7 KB/sec)
    [INFO] Downloaded: http://repo.maven.apache.org/maven2/org/codehaus/mojo/maven-metadata.xml (20 KB at 4.0 KB/sec)
    [INFO] ————————————————————————
    [INFO] BUILD FAILURE
    [INFO] ————————————————————————
    [INFO] Total time: 5.847 s
    [INFO] Finished at: 2015-04-11T11:02:04+05:30
    [INFO] Final Memory: 8M/179M
    [INFO] ————————————————————————
    [ERROR] No plugin found for prefix ‘appengine’ in the current project and in the plugin groups [org.apache.maven.plugins, org.codehaus.mojo] available from the repositories [local (C:\Users\rn016\.m2\repository), central (http://repo.maven.apache.org/maven2)] -> [Help 1]
    [ERROR]
    [ERROR] To see the full stack trace of the errors, re-run Maven with the -e switch.
    [ERROR] Re-run Maven using the -X switch to enable full debug logging.
    [ERROR]
    [ERROR] For more information about the errors and possible solutions, please read the following articles:
    [ERROR] [Help 1] http://cwiki.apache.org/confluence/display/MAVEN/NoPluginFoundForPrefixException

    I am using the eclispe luna 4.4 and maven

    1. ahmad says:

      can u teach me..what should i write in com.model of upload file

  25. sliman says:

    Thank You !

  26. mohit says:

    File Directory created to be used for storing files
    java.io.FileNotFoundException: D:\Mohit\New folder\D:\Mohit\data.laccdb (The filename, directory name, or volume label syntax is incorrect)
    at java.io.FileOutputStream.open(Native Method)
    at java.io.FileOutputStream.(Unknown Source)
    at java.io.FileOutputStream.(Unknown Source)
    at org.apache.commons.fileupload.disk.DiskFileItem.write(DiskFileItem.java:394)
    at UploadDownloadFileServlet.doPost(UploadDownloadFileServlet.java:110)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:646)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:727)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:303)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:208)
    at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:241)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:208)
    at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:220)
    at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:122)
    at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:503)
    at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:170)
    at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:103)
    at org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:950)
    at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:116)
    at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:421)
    at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1070)
    at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:611)
    at org.apache.tomcat.util.net.JIoEndpoint$SocketProcessor.run(JIoEndpoint.java:314)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source)
    at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
    at java.lang.Thread.run(Unknown Source)
    FieldName=fileName
    FileName=D:\Mohit\data.laccdb
    ContentType=text/plain
    Size in bytes=256
    Absolute Path at server=D:\Mohit\New folder\D:\Mohit\data.laccdb

    1. van do says:

      add libarary into Webapp Library

  27. kapil says:

    Hi Pankaj ,

    when i am uploading more than 1mb file ,I am geetting a emplty list on below line.
    List fileItemsList = uploader.parseRequest(request);

    but for less than 1mb file it is working fine.

    plz help me.

  28. gauri says:

    Hello Pankaj,

    My aim is to upload an encrypted file to server. So what modification should i do in this basic code?

    I need to select a file, do aes encryption at client side and then after encryption upload encrypted file to server. Again to retreive the file, do the decryption at client side.

    Please help me.

  29. surendar says:

    File file = new File(request.getServletContext().getAttribute(“FILES_DIR_FILE”)+File.separator+fileName);

    In this Line i get “The method getServletContext() is undefined for the type HttpServletRequest”

    1. Ajit says:

      You may simply call
      getServletContext().getAttribute(“FILES_DIR_FILE”)

      1. SMITH says:

        getServletContext().getAttribute(“FILES_DIR”) IS NOT WORKING

    2. Sandeep says:

      Make Sure that you are using Tomcat version 7 or more than that.

      1. Sandeep says:

        And also check the Java version..Please make sure that you are using java 8

  30. satya says:

    I am getting this exception, Please help me……..

    Exception in uploading file.java.io.FileNotFoundException: C:\apache-tomcat-7.0.14\tmpfiles (Access is denied)

  31. Ritu says:

    everytime i click on upload file. it shows “Exception in uploading file.”
    what do i do pls help.
    thanks

  32. Ritu says:

    i am not able to download the zipfile of this project

  33. Tutorial Java Untuk Pemula says:

    Good Tutorial, thanks

    1. gabi says:

      In worder to get the correct file name i must use this
      FilenameUtils.getName(fileItem.getName()

  34. Sim says:

    Thanks so much for the tutorial. However I noticed that these is not supported in IE. I mean the upload part. What could be wrong

    1. Pankaj says:

      I haven’t tested it with IE, but I suspect this might be because of Content-Type header, please print request header details to figure out anything wrong with it?

  35. Snehal says:

    I have one jsp page containing browse button and tag. When i browse a file i want to populate the with users name containing in the file. And i am sending file name through jQuery. But on servlet i’m getting file name as C:/fakepath/Users.xls. How can i get the original path? How can i populate my box with users list.

  36. john says:

    i tried the codes above and i got this :

    javax.servlet.ServletException: File Name can’t be null or empty
    journaldev.UploadDownloadFileServlet.doGet(UploadDownloadFileServlet.java:38)
    javax.servlet.http.HttpServlet.service(HttpServlet.java:618)
    javax.servlet.http.HttpServlet.service(HttpServlet.java:725)
    org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)

  37. mahendra says:

    Hi,

    I am unable to upload my image. That is giving me Exception please help me to resolve my problem…

    EXCEPTION : /usr/local/tomcat/apache-tomcat-6.0.36/bin/null/uploadFile/images.jpg (No such file or directory)

  38. Jadhav says:

    Hello Pankaj,
    I got such an exception while clicking on Upload button. Please help me.
    org.apache.jasper.JasperException: An exception occurred processing JSP page /upload.jsp at line 39

    36: byte[] bFile = new byte[(int) file1.length()];
    37:
    38: //convert file into array of bytes
    39: fis = new FileInputStream(file1);
    40: fout = new FileOutputStream(“E:\\Temp\\file1.txt”);
    41: fout1 = new FileOutputStream(“E:\\Temp\\file2.txt”);
    42: fout2 = new FileOutputStream(“E:\\Temp\\file3.txt”);

    root cause

    java.io.FileNotFoundException: E:\File\copy-right-form.doc (The system cannot find the path specified)
    java.io.FileInputStream.open(Native Method)
    java.io.FileInputStream.(FileInputStream.java:138)
    org.apache.jsp.upload_jsp._jspService(upload_jsp.java:115)
    org.apache.jasper.runtime.HttpJspBase.service(HttpJspBase.java:70)
    javax.servlet.http.HttpServlet.service(HttpServlet.java:722)
    org.apache.jasper.servlet.JspServletWrapper.service(JspServletWrapper.java:432)
    org.apache.jasper.servlet.JspServlet.serviceJspFile(JspServlet.java:390)
    org.apache.jasper.servlet.JspServlet.service(JspServlet.java:334)
    javax.servlet.http.HttpServlet.service(HttpServlet.java:722)

  39. krishna kumar says:

    Hello Pankaj,
    I got such an exception while clicking on Upload button. Please help me.

    org.apache.commons.fileupload.FileUploadBase$IOFileUploadException: Processing of multipart/form-data request failed. C:\Program Files\Apache Software Foundation\Tomcat 7.0\null\upload_2b1a313c_147347faa4e__7ffe_00000000.tmp (The system cannot find the path specified)
    at org.apache.commons.fileupload.FileUploadBase.parseRequest(FileUploadBase.java:367)
    at org.apache.commons.fileupload.servlet.ServletFileUpload.parseRequest(ServletFileUpload.java:126)

    I have pasted a part of exception only.
    Thank You!

    1. Pankaj says:

      Read the exception, it clearly says that system is not able to find the path. I think C:\Program Files\Apache Software Foundation\Tomcat 7.0\null\ directory is not present.

      Quick Tip: Always avoid white space in directory names, it causes a lot of trouble, trust me.

      1. krishna kumar says:

        I corrected that null, but still have same problem like this..

        org.apache.commons.fileupload.FileUploadBase$IOFileUploadException: Processing of multipart/form-data request failed. C:\Program Files\Apache Software Foundation\Tomcat 7.0\tempfile\upload_2b1a313c_147347faa4e__7ffe_00000000.tmp (The system cannot find the path specified)

    2. Pastis says:

      Hi,

      of course!
      for the tmp directory to be created by the context
      the ServletContextListener has to be declared in the web.xml file it’s not enough
      to just create the class implementation.

      you should add to the web.xml

      ….
      …. / / other stuff here
      ….

      com.journaldev.servlet.FileLocationContextListener // or the name of the package
      // and class you chose

  40. sam says:

    mr.pankaj
    thanks for your post.
    here i get error in these lines … even after adding servlet api .jar file
    //import javax.servlet.annotation.WebListener;
    //@WebListener
    in both java class

    and also getting error in getservletcontext() function..

    how to resolve it.
    will it work only if v use tomact version 7…?

    1. Pankaj says:

      These annotations are part of Servlet Spec 3.0, so you need to add corresponding jar file. Apache Tomcat 7 supports Servlet 3, thats why it works with it.

  41. Pooria says:

    hello.
    why you say

    if(!ServletFileUpload.isMultipartContent(request)){
    throw new ServletException(“Content type is not multipart/form-data”);
    }
    ?

  42. Vladimir says:

    Hi, Pankaj!

    Why you did not include FileLocationContextListener in web.xml like this?

    com.journaldev.servlet.FileLocationContextListener

    1. Pankaj says:

      Because I am using Servlet-3 annotation @WebListener for listener. So we dont need to add listener class in the web.xml configuration. If you are using XML based configuration, you should do it in the web.xml file and remove annotation.

  43. Arab says:

    Thanks for sharing , but when I press the upload button the 404 erorr is shown,,please help and how to fix it .

    1. Pankaj says:

      You must have been pointing to wrong Servlet URI, please check that.

      1. Arab says:

        As u said ,, Servlet URI was wrong, ann I have already also problem with import java.io and javax.servlets API.

        now every thing work perfectly,, curently I am trying to configure your code so that I can upload a project or package not only single file. It is possible right ?

        Thanks in advance 🙂

  44. Andrew Nguyen says:

    Hello, first off thank you for all these tutorials! really helpful

    So I am having trouble figuring out a way to renaming the file name using this approach. There is no fileItem.setName() so is there another way we can rename the file before uploading it to the directory?

    1. Pankaj says:

      File file = new File(request.getServletContext().getAttribute(“FILES_DIR”)+File.separator+fileItem.getName());

      You can change the name here.

  45. ronlad says:

    hi Pankaj, thank for your tutorial,
    please i need help.

    I would like change de directory of my file
    i have this :
    Absolute Path at server=C:\Users\Ronald\Desktop\eclipseAjour\eclipse\null\WWW.YIFY-TORRENTS.COM.jpg
    File location on server::C:\Users\Ronald\Desktop\eclipseAjour\eclipse\null\WWW.YIFY-TORRENTS.COM.jpg
    File downloaded at client successfully

    and i would like to put my image in other directory

    here:

    C:\Users\Ronald\workspace\ServletUpload\src\com\image

    thank for your help and have a good day.

    1. Pankaj says:

      You can put any file location, read file path from a properties file.

  46. Kiran says:

    Hi Pankaj,
    It’s really nice tutorial you have posted. It’s worked for me. thanks.

  47. Charan says:

    When i click on upload button it is showing Exception in uploading file

  48. Charan says:

    List fileItemsList = uploader.parseRequest(request);

    Im getting error in the above line saying that;

    required:RequestContext
    found:HttpServletRequest
    reason:actual arguements HttpServletRequest cannot be converted to RequestContext by method invocation conversion

    1. Kamiel Ahmadpour says:

      You need to import from apache commons and not tomcat

      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;

      1. Preet says:

        @Kamiel Ahmadpour – It solved my problem which i was facing for a week and spending a long on my program and on internet.. your answer helped me a lot.. Thank you Sir.

  49. Sanjay says:

    Im gettin g this error when i browse for a file and click upload. Pls help me asap.

    Im just trying to upload a jar file(tightvnc-jviewer.jar). Im not able to upload any type of file. It gives me the same exception everytime.

    Absolute Path at server=D:\Sanjay\Softwares\apache-tomcat-7.0.53\apache-tomcat-7.0.53\tmpfiles\D:\Sanjay\Softwares\tightvnc-jviewer.jar

    java.io.FileNotFoundException: D:\Sanjay\Softwares\apache-tomcat-7.0.53\apache-tomcat-7.0.53\tmpfiles\D:\Sanjay\Softwares\tightvnc-jviewer.jar (The filename, directory name, or volume label syntax is incorrect)
    at java.io.FileOutputStream.open(Native Method)
    at java.io.FileOutputStream.(FileOutputStream.java:179)
    at java.io.FileOutputStream.(FileOutputStream.java:131)
    at org.apache.commons.fileupload.disk.DiskFileItem.write(DiskFileItem.java:417)
    at com.journaldev.servlet.UploadDownloadFileServlet.doPost(UploadDownloadFileServlet.java:85)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:646)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:727)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:303)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:208)
    at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:220)
    at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:122)
    at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:501)
    at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:170)
    at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:98)
    at org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:950)
    at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:116)
    at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:408)
    at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1040)
    at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:607)
    at org.apache.tomcat.util.net.JIoEndpoint$SocketProcessor.run(JIoEndpoint.java:313)
    at java.util.concurrent.ThreadPoolExecutor$Worker.runTask(ThreadPoolExecutor.java:886)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:908)
    at java.lang.Thread.run(Thread.java:619)

    1. Pankaj says:

      The console log clearly shows D: drive in the file location two times, please check your directory location configurations.

  50. Diksha says:

    Sir if i m using glassfish then servlet is not found error is reflected can u help me in this is it mandatory to use glassfish?

    1. Pankaj says:

      Can you provide the exact error in server log? Try adding servlet-api jar in the project, usually it’s part of the container and we don’t need to add it.

  51. Sonerao JAdhav says:

    Hello i am sonerao and very thank You for sharing this File upload Code it very Help full.
    But at the time of code importing is giving some error.
    i’m download u r .zip file and this file i import as it is into my eclipse it will be import success fully but it will give an error at the time of Project Deployment i have a app-ache tomcat 6.0.

    So Can u Give some Conclusion .thank You

  52. ana says:

    erro getServletContext() ?????

  53. Hareesh says:

    it showing an error—–import javax.servlet.annotation.WebListener; (cannot be resolved).

    @WebListener (cannot be resolved a type)

    1. Pankaj says:

      That is because you don’t have servlet-api jar in the build path. When I create “Dynamic Web Project” in Eclipse and choose runtime as Tomcat-7 that is added in my Eclipse Servers, the tomcat lib is added in the build path of the project having servlet-api jar and therefore no build/compile issues.

      1. sudarshan says:

        i want to fileuploading along with form data. i faced mediatype not supported problem

  54. msaahish says:

    hi i want to upload images by creating folder with username and upload image to username folder for every user like that.

  55. zanyar says:

    hi

    i want help me for upload files with details information after that send data to database with information bellow by JSP
    like
    (File_ID, File_name, File_Description,Date_file, Upload_file)
    if any persons help me

  56. ganesh says:

    i am create java website in eclipse, sql server 2008 r2 for database for servlet to database i use type 4 connectivity by using sql_jdbc 4 driver but they show me com.microsoft.sqlserver.jdbc.sqlserverexception but ping was succeed…………….what i do please help me

  57. Devendra says:

    I have tried this example the upload part is fine. But the while downloading the file is always saved as UploadDownloadFileServlet with no extension so the file is not readable. Any suggestion …. ?

    Ex when I click on Download “books.pdf” it saved as UploadDownloadFileServlet

    1. Pankaj says:

      Did you make any changes to the program? I run it again and it’s working fine for me.

  58. pralabh says:

    sometimes on downloading file on client side, servlet gives content length -1 but file keeps on downloading. Any suggestions?

    1. Pankaj says:

      it must be related to file IO operations, add some logging statements and then check it.

Leave a Reply

Your email address will not be published. Required fields are marked *

close
Generic selectors
Exact matches only
Search in title
Search in content
Search in posts
Search in pages