Tutorial

Servlet 3 File Upload - @MultipartConfig, Part

Published on August 4, 2022
author

Pankaj

Servlet 3 File Upload - @MultipartConfig, Part

Today we will look into Servlet 3 File Upload Example using @MultipartConfig annotation and javax.servlet.http.Part. Sometime back I wrote an article about Servlet File Upload and I used Apache FileUpload API but here we will use Servlet 3 File Upload feature.

Servlet 3 File Upload

Since File Upload is a common task in web applications, Servlet Specs 3.0 provided additional support for uploading files to server and we don’t have to depend on any third party APIs for this. In this tutorial we will see how we can use Servlet 3.0 API for uploading Files to server.

MultipartConfig

We need to annotate File Upload handler servlet with MultipartConfig annotation to handle multipart/form-data requests that is used for uploading file to server. MultipartConfig annotation has following attributes:

  • fileSizeThreshold: We can specify the size threshold after which the file will be written to disk. The size value is in bytes, so 1024*1024*10 is 10 MB.
  • location: Directory where files will be stored by default, it’s default value is “”.
  • maxFileSize: Maximum size allowed to upload a file, it’s value is provided in bytes. It’s default value is -1L means unlimited.
  • maxRequestSize: Maximum size allowed for multipart/form-data request. Default value is -1L that means unlimited.

Read more about annotations at Java Annotations Tutorial.

Part Interface

Part interface represents a part or form item that was received within a multipart/form-data POST request. Some important methods are getInputStream(), write(String fileName) that we can use to read and write file.

HttpServletRequest Changes

New methods got added in HttpServletRequest to get all the parts in multipart/form-data request through getParts() method. We can get a specific part using getPart(String partName) method. Let’s see a simple project where we will use above API methods to upload file using servlet. Our project structure will look like below image. Servlet 3 File Upload, @MultipartConfig, javax.servlet.http.Part

HTML Form

We have a simple html page where we can select the file to upload and submit request to server to get it uploaded. index.html

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

File Upload Servlet

Here is our File Upload Servlet implementation. FileUploadServlet.java

package com.journaldev.servlet;
 
import java.io.File;
import java.io.IOException;
 
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;
 
@WebServlet("/FileUploadServlet")
@MultipartConfig(fileSizeThreshold=1024*1024*10, 	// 10 MB 
                 maxFileSize=1024*1024*50,      	// 50 MB
                 maxRequestSize=1024*1024*100)   	// 100 MB
public class FileUploadServlet extends HttpServlet {
 
    private static final long serialVersionUID = 205242440643911308L;
	
    /**
     * Directory where uploaded files will be saved, its relative to
     * the web application directory.
     */
    private static final String UPLOAD_DIR = "uploads";
     
    protected void doPost(HttpServletRequest request,
            HttpServletResponse response) throws ServletException, IOException {
        // gets absolute path of the web application
        String applicationPath = request.getServletContext().getRealPath("");
        // constructs path of the directory to save uploaded file
        String uploadFilePath = applicationPath + File.separator + UPLOAD_DIR;
         
        // creates the save directory if it does not exists
        File fileSaveDir = new File(uploadFilePath);
        if (!fileSaveDir.exists()) {
            fileSaveDir.mkdirs();
        }
        System.out.println("Upload File Directory="+fileSaveDir.getAbsolutePath());
        
        String fileName = null;
        //Get all the parts from request and write it to the file on server
        for (Part part : request.getParts()) {
            fileName = getFileName(part);
            part.write(uploadFilePath + File.separator + fileName);
        }
 
        request.setAttribute("message", fileName + " File uploaded successfully!");
        getServletContext().getRequestDispatcher("/response.jsp").forward(
                request, response);
    }
 
    /**
     * Utility method to get file name from HTTP header content-disposition
     */
    private String getFileName(Part part) {
        String contentDisp = part.getHeader("content-disposition");
        System.out.println("content-disposition header= "+contentDisp);
        String[] tokens = contentDisp.split(";");
        for (String token : tokens) {
            if (token.trim().startsWith("filename")) {
                return token.substring(token.indexOf("=") + 2, token.length()-1);
            }
        }
        return "";
    }
}

Notice the use of @MultipartConfig annotation to specify different size parameters for upload file. We need to use request header “content-disposition” attribute to get the file name sent by client, we will save the file with same name. The directory location is relative to web application where I am saving the file, you can configure it to some other location like in Apache Commons FileUpload example.

Response JSP

A simple JSP page that will be sent as response to client once the file is uploaded successfully to server. response.jsp

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
    pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" 
    "https://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<title>Upload File Response</title>
</head>
<body>
	<%-- Using JSP EL to get message attribute value from request scope --%>
    <h2>${requestScope.message}</h2>
</body>
</html>

Deployment Descriptor

There is nothing new in web.xml file for servlet file upload, it’s only used to make the index.html as welcome file. web.xml

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="https://www.w3.org/2001/XMLSchema-instance" xmlns="https://java.sun.com/xml/ns/javaee" xsi:schemaLocation="https://java.sun.com/xml/ns/javaee https://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" version="3.0">
  <display-name>ServletFileUploadExample</display-name>
  <welcome-file-list>
    <welcome-file>index.html</welcome-file>
  </welcome-file-list>
</web-app>

Now when we run the application, we get following pages as response. Servlet 3 File Upload HTML Servlet 3 File Upload Success The logs will show the directory location where file is saved and content-disposition header information.

Upload File Directory=/Users/pankaj/Documents/workspace/j2ee/.metadata/.plugins/org.eclipse.wst.server.core/tmp0/wtpwebapps/ServletFileUploadExample/uploads
content-disposition header= form-data; name="fileName"; filename="IMG_2046.jpg"

I am running Tomcat through Eclipse, that’s why file location is like this. If you run tomcat through command line and deploy application by exporting as WAR file into webapps directory, you will get different structure but a clear one.

Download Servlet 3 Multipart File Upload Project

Thanks for learning with the DigitalOcean Community. Check out our offerings for compute, storage, networking, and managed databases.

Learn more about our products

About the author(s)

Category:
Tutorial

While we believe that this content benefits our community, we have not yet thoroughly reviewed it. If you have any suggestions for improvements, please let us know by clicking the “report an issue“ button at the bottom of the tutorial.

Still looking for an answer?

Ask a questionSearch for more help

Was this helpful?
 
JournalDev
DigitalOcean Employee
DigitalOcean Employee badge
January 5, 2014

What if a user tries to access the Servlet directly? The @MultipartConfig fails what can be done in that case?

- Arun

    JournalDev
    DigitalOcean Employee
    DigitalOcean Employee badge
    January 5, 2014

    I am getting Servlet.service() for servlet [com.journaldev.servlet.FileUploadServlet] in context with path [/Assign1] threw exception java.io.IOException: java.io.FileNotFoundException pls help me!!..

    - suraj

    JournalDev
    DigitalOcean Employee
    DigitalOcean Employee badge
    January 6, 2014

    Can you tell me the URL you are trying to access?

    - Pankaj

    JournalDev
    DigitalOcean Employee
    DigitalOcean Employee badge
    January 6, 2014

    https://localhost:8080/Assign1/

    - suraj

    JournalDev
    DigitalOcean Employee
    DigitalOcean Employee badge
    January 6, 2014

    That’s why you are getting the exception, there is no resources (Servlet) configured to handle the URL you are trying to access. Please check the images to get the URL to run the application successfully.

    - Pankaj

    JournalDev
    DigitalOcean Employee
    DigitalOcean Employee badge
    August 13, 2014

    The Above Code Not Working Properly in IE Please Check and provide Solution sir.

    - Manoj

      JournalDev
      DigitalOcean Employee
      DigitalOcean Employee badge
      January 20, 2014

      Hello Pankaj, Thanks for tutorial. but i want to download the text file from server using same multipart or servlet 3.0, can use please provide me with the same?

      - Sushank Dahiwadkar

        JournalDev
        DigitalOcean Employee
        DigitalOcean Employee badge
        January 24, 2014

        one more thing ! plz share reply for this time on my mail id. cause for a very few moments i can access other sites at my workstation.plz.

        - prashant

        JournalDev
        DigitalOcean Employee
        DigitalOcean Employee badge
        January 24, 2014

        I think below for loop with take care of multiple files automatically. for (Part part : request.getParts()) { fileName = getFileName(part); part.write(uploadFilePath + File.separator + fileName); } I haven’t tested it though, please check.

        - Pankaj

        JournalDev
        DigitalOcean Employee
        DigitalOcean Employee badge
        May 17, 2014

        It’s ok, but if one of those file controls is empty, servlet crashes. I don’t know how fix it :(

        - freyaa

          JournalDev
          DigitalOcean Employee
          DigitalOcean Employee badge
          February 10, 2014

          Thanx 4 ur code it really helpful. Will u please tell me hoe to upload multiple files and store it into database and later download them

          - Kedar

          JournalDev
          DigitalOcean Employee
          DigitalOcean Employee badge
          February 10, 2014

          You can easily extend the program to store the files in Database using JDBC Connections.

          - Pankaj

            JournalDev
            DigitalOcean Employee
            DigitalOcean Employee badge
            April 4, 2014

            I want to integrate it in my project so what is the jar file I need to use. .

            - Raghavendra M

            JournalDev
            DigitalOcean Employee
            DigitalOcean Employee badge
            April 4, 2014

            Use servlet-api jar from Tomcat7, that implements Servlet-3 specs.

            - Pankaj

              JournalDev
              DigitalOcean Employee
              DigitalOcean Employee badge
              April 4, 2014

              What is the jar file I need to use .

              - Raghavendra M

                JournalDev
                DigitalOcean Employee
                DigitalOcean Employee badge
                April 4, 2014

                Now I want to display image on jsp which is stored on server . . . how to do that … can u send some code sample . .

                - Raghavendra M

                  JournalDev
                  DigitalOcean Employee
                  DigitalOcean Employee badge
                  April 7, 2014

                  Hi I am using file upload along with other textfiled. My problem is, if I submit form as multipart/form-data all text fields will be null for getParameter() . So how to get the value of textfields when v send form as multipart/form-data.

                  - Raghavendra M

                    JournalDev
                    DigitalOcean Employee
                    DigitalOcean Employee badge
                    April 23, 2014

                    Thanks Buddy Your code help me and its work better.

                    - Ravi

                      JournalDev
                      DigitalOcean Employee
                      DigitalOcean Employee badge
                      June 8, 2014

                      Hi Pankaj, When I run this project using Glassfish 4.0 I end up with below error. It would be great if you could help to solve this. Thanks, Reginald HTTP Status 500 - Internal Server Error type Exception report messageInternal Server Error descriptionThe server encountered an internal error that prevented it from fulfilling this request. exception java.io.FileNotFoundException: C:\Users\Reginald\AppData\Roaming\NetBeans\7.4\config\GF_4.0\domain1\generated\jsp\FileUpl\C:\Users\Reginald\Documents\NetBeansProjects\FileUpl\build\web\uploads\C:\Users\Reginald\Documents\javaeetutorial6.pdf (The filename, directory name or volume label syntax is incorrect) note The full stack traces of the exception and its root causes are available in the GlassFish Server Open Source Edition 4.0 logs.

                      - Reginald Bal

                      JournalDev
                      DigitalOcean Employee
                      DigitalOcean Employee badge
                      June 8, 2014

                      As you can see from logs, its FileNotFoundException and the reason is very clear, notice C:\ is occurring two times in the file path, please check how you are setting this.

                      - Pankaj

                      JournalDev
                      DigitalOcean Employee
                      DigitalOcean Employee badge
                      June 23, 2014

                      i have the same error… and if you see i use only once the request.getServletContext().getRealPath(""); `` `package servlets; import java.io.File; import java.io.IOException; import java.io.InputStream; 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 SL_Solicitud_STE_Foto */ @WebServlet("/SL_Solicitud_STE_Foto") @MultipartConfig(fileSizeThreshold = 1024 * 1024 * 2, // 2MB maxFileSize = 1024 * 1024 * 10, // 10MB maxRequestSize = 1024 * 1024 * 50,// 50MB location="/" ) public class SL_Solicitud_STE_Foto extends HttpServlet { private static final long serialVersionUID = 1L; private static final String SAVE_DIR = "foto"; /** * @see HttpServlet#HttpServlet() */ public SL_Solicitud_STE_Foto() { 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 { // TODO Auto-generated method stub //--------------------------------------------------------------------------------------------- // gets absolute path of the web application String applicationPath = request.getServletContext().getRealPath(""); // constructs path of the directory to save uploaded file String uploadFilePath = applicationPath + File.separator + SAVE_DIR; // creates the save directory if it does not exists File fileSaveDir = new File(uploadFilePath); if (!fileSaveDir.exists()) { System.out.println("NO EXISTE"); System.out.println("CREA: "+fileSaveDir.mkdirs()); } System.out.println("Upload File Directory="+fileSaveDir.getAbsolutePath()); String fileName = null; //Get all the parts from request and write it to the file on server for (Part part : request.getParts()) { fileName = getFileName(part); part.write(uploadFilePath + File.separator + fileName); } request.setAttribute("message", fileName + " File uploaded successfully!"); getServletContext().getRequestDispatcher("/Solicitud_STE_Foto.jsp").forward( request, response); } /** * Utility method to get file name from HTTP header content-disposition */ private String getFileName(Part part) { String contentDisp = part.getHeader("content-disposition"); System.out.println("content-disposition header= "+contentDisp); String[] tokens = contentDisp.split(";"); for (String token : tokens) { if (token.trim().startsWith("filename")) { return token.substring(token.indexOf("=") + 2, token.length()-1); } } return ""; } }` here is the stacktrace `2014-06-23T14:58:22.030-0600|INFO: content-disposition header= form-data; name="file"; filename="scary_joker.jpg" 2014-06-23T14:58:22.031-0600|WARNING: StandardWrapperValve[servlets.SL_Solicitud_STE_Foto]: Servlet.service() for servlet servlets.SL_Solicitud_STE_Foto threw exception java.io.FileNotFoundException: C:\Users\Sami Al Masagedi\Desktop\glassfish4\glassfish\domains\domain1\generated\jsp\prematriculaonline\C:\Users\Sami Al Masagedi\Desktop\glassfish4\glassfish\domains\domain1\eclipseApps\prematriculaonline\foto\scary_joker.jpg (The filename, directory name, or volume label syntax is incorrect) at java.io.FileOutputStream.open(Native Method) at java.io.FileOutputStream.(FileOutputStream.java:221) at java.io.FileOutputStream.(FileOutputStream.java:171) at org.apache.catalina.fileupload.PartItem.write(PartItem.java:450) at org.apache.catalina.fileupload.PartItem.write(PartItem.java:505) at servlets.SL_Solicitud_STE_Foto.doPost(SL_Solicitud_STE_Foto.java:68) at javax.servlet.http.HttpServlet.service(HttpServlet.java:707) at javax.servlet.http.HttpServlet.service(HttpServlet.java:790) at org.apache.catalina.core.StandardWrapper.service(StandardWrapper.java:1682) at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:318) at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:160) at org.apache.catalina.core.StandardPipeline.doInvoke(StandardPipeline.java:734) at org.apache.catalina.core.StandardPipeline.invoke(StandardPipeline.java:673) at com.sun.enterprise.web.WebPipeline.invoke(WebPipeline.java:99) at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:174) at org.apache.catalina.connector.CoyoteAdapter.doService(CoyoteAdapter.java:357) at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:260) at com.sun.enterprise.v3.services.impl.ContainerMapper.service(ContainerMapper.java:188) at org.glassfish.grizzly.http.server.HttpHandler.runService(HttpHandler.java:191) at org.glassfish.grizzly.http.server.HttpHandler.doHandle(HttpHandler.java:168) at org.glassfish.grizzly.http.server.HttpServerFilter.handleRead(HttpServerFilter.java:189) at org.glassfish.grizzly.filterchain.ExecutorResolver$9.execute(ExecutorResolver.java:119) at org.glassfish.grizzly.filterchain.DefaultFilterChain.executeFilter(DefaultFilterChain.java:288) at org.glassfish.grizzly.filterchain.DefaultFilterChain.executeChainPart(DefaultFilterChain.java:206) at org.glassfish.grizzly.filterchain.DefaultFilterChain.execute(DefaultFilterChain.java:136) at org.glassfish.grizzly.filterchain.DefaultFilterChain.process(DefaultFilterChain.java:114) at org.glassfish.grizzly.ProcessorExecutor.execute(ProcessorExecutor.java:77) at org.glassfish.grizzly.nio.transport.TCPNIOTransport.fireIOEvent(TCPNIOTransport.java:838) at org.glassfish.grizzly.strategies.AbstractIOStrategy.fireIOEvent(AbstractIOStrategy.java:113) at org.glassfish.grizzly.strategies.WorkerThreadIOStrategy.run0(WorkerThreadIOStrategy.java:115) at org.glassfish.grizzly.strategies.WorkerThreadIOStrategy.access$100(WorkerThreadIOStrategy.java:55) at org.glassfish.grizzly.strategies.WorkerThreadIOStrategy$WorkerThreadRunnable.run(WorkerThreadIOStrategy.java:135) at org.glassfish.grizzly.threadpool.AbstractThreadPool$Worker.doWork(AbstractThreadPool.java:564) at org.glassfish.grizzly.threadpool.AbstractThreadPool$Worker.run(AbstractThreadPool.java:544) at java.lang.Thread.run(Thread.java:744)` ``

                      - Sami

                        JournalDev
                        DigitalOcean Employee
                        DigitalOcean Employee badge
                        June 9, 2014

                        For everyone who has problems with FileNotFoundException due to double path. Try adding “location” to @MultipartConfig, like this: @MultipartConfig(fileSizeThreshold=1024*1024*10, // 10 MB maxFileSize=1024*1024*50, // 50 MB maxRequestSize=1024*1024*100, // 100 MB location=“/” ) works for me.

                        - Andac

                        JournalDev
                        DigitalOcean Employee
                        DigitalOcean Employee badge
                        September 29, 2017

                        You are right. I met this problem when using IntelliJ IDE on MAC. Thank you Andac

                        - Peter Tran

                          JournalDev
                          DigitalOcean Employee
                          DigitalOcean Employee badge
                          June 23, 2014

                          Sir m getting a painful error when m accessing the URL HTTP Status 404 - Not Found type Status report messageNot Found descriptionThe requested resource is not available. GlassFish Server Open Source Edition 4.0 URL is : https://localhost:8080/WebApplication2/ I dont knw what to do wid it . M pestered

                          - Aakanksha

                            JournalDev
                            DigitalOcean Employee
                            DigitalOcean Employee badge
                            July 11, 2014

                            when i click on the upload button it shows http status 404 error desrciption :requested resource is not available. apache tomcat /7.0.54 plz help me out …

                            - praveen

                              JournalDev
                              DigitalOcean Employee
                              DigitalOcean Employee badge
                              August 6, 2014

                              Hi, Thanks for the info, it really helped me a lot. Can you help me to retrieve these files from the database and display it using jap. Thanks in advance.

                              - Kiran G V

                                JournalDev
                                DigitalOcean Employee
                                DigitalOcean Employee badge
                                August 13, 2014

                                Hai Sir, There is problem in Content Disposition in IE the filename is takeing differently when compared to other browser please fine and provide solution.The Above code not work properly in IE.

                                - Manoj

                                JournalDev
                                DigitalOcean Employee
                                DigitalOcean Employee badge
                                August 13, 2014

                                Can you post what is the value coming in case of IE, I think you can find browser information from the request header and handle it accordingly.

                                - Pankaj

                                  JournalDev
                                  DigitalOcean Employee
                                  DigitalOcean Employee badge
                                  October 26, 2014

                                  This worked perfectly! Thank you so much for your work!!

                                  - Bob

                                    JournalDev
                                    DigitalOcean Employee
                                    DigitalOcean Employee badge
                                    November 13, 2014

                                    pankaj I am getting this error.please any one tell me how to solve it as soon as possible. SEVERE: Servlet.service() for servlet [FileUploadServlet] in context with path [/ems] threw exception java.io.IOException: java.io.FileNotFoundException: C:\apache-tomcat-7.0.56-windows-x64\apache-tomcat-7.0.56\wtpwebapps\ems\uploads\C:\Users\hello\Pictures\image002.jpg (The filename, directory name, or volume label syntax is incorrect) at org.apache.catalina.core.ApplicationPart.write(ApplicationPart.java:121) at FileUploadServlet.doPost(FileUploadServlet.java:44) 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: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$Worker.runTask(ThreadPoolExecutor.java:886) at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:908) at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61) at java.lang.Thread.run(Thread.java:662) Caused by: java.io.FileNotFoundException: C:\apache-tomcat-7.0.56-windows-x64\apache-tomcat-7.0.56\wtpwebapps\ems\uploads\C:\Users\hello\Pictures\image002.jpg (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.tomcat.util.http.fileupload.disk.DiskFileItem.write(DiskFileItem.java:377) at org.apache.catalina.core.ApplicationPart.write(ApplicationPart.java:119) … 20 more

                                    - Hariharanadh

                                    JournalDev
                                    DigitalOcean Employee
                                    DigitalOcean Employee badge
                                    January 27, 2015

                                    Can you please post your FileUploadServlet servlet code please?

                                    - Mingle

                                      JournalDev
                                      DigitalOcean Employee
                                      DigitalOcean Employee badge
                                      January 27, 2015

                                      Nevermind, do not post your code. You have two C:/'s in your ‘path’.

                                      - Mingle

                                        JournalDev
                                        DigitalOcean Employee
                                        DigitalOcean Employee badge
                                        December 17, 2014

                                        I was uploaded video using this (request.getServletContext().getRealPath(“”);) path.Uploaded work.but how can i preview in jsp.${pagecontex.request.getRealPath(path)} wasn’t work.If any help for uploaded video need to play inside jsp using Video tag

                                        - Madhawa

                                          JournalDev
                                          DigitalOcean Employee
                                          DigitalOcean Employee badge
                                          January 6, 2015

                                          Thanks Pankaj,This example works fine…

                                          - Deepak

                                            JournalDev
                                            DigitalOcean Employee
                                            DigitalOcean Employee badge
                                            March 25, 2015

                                            Hi Pankaj, Thanks for the tutorial. it works for me. Learnt a lot. i have a problem. i have to upload text files those have multi-lingual data in them. so i need to write the filer in UTF-8 format. but part.write function does not have provision for that. Can you help me in this? Thanks in advance.

                                            - Gouravmoy Mohanty

                                              JournalDev
                                              DigitalOcean Employee
                                              DigitalOcean Employee badge
                                              April 28, 2015

                                              can your code work on https servers? it works on http but it stops when i try it on https… is it possible to upload and write a file on a server which is accessed with https ? thanks very much for your answer!

                                              - Ariane

                                                JournalDev
                                                DigitalOcean Employee
                                                DigitalOcean Employee badge
                                                June 26, 2015

                                                This is Servlet 3.1 not 3.0. There is no getFileName in 3.0

                                                - Koray Tugay

                                                  JournalDev
                                                  DigitalOcean Employee
                                                  DigitalOcean Employee badge
                                                  July 27, 2015

                                                  Hi To All, Can anyone tell me, how to update the existing file from specific folder in jsp/servlet and how to check whether the file is empty or not.

                                                  - Imran Basha

                                                    JournalDev
                                                    DigitalOcean Employee
                                                    DigitalOcean Employee badge
                                                    December 15, 2015

                                                    it says this package does not exit “import javax.servlet.annotation.MultipartConfig;”,“import javax.servlet.annotation.WebServlet; import javax.servlet.http.Part;” i m using netbeans 6.8,plz help

                                                    - vicky

                                                    JournalDev
                                                    DigitalOcean Employee
                                                    DigitalOcean Employee badge
                                                    December 15, 2015

                                                    add servlet-api jars in your project, or you can add a server runtime to the project to have these jars.

                                                    - Pankaj

                                                      JournalDev
                                                      DigitalOcean Employee
                                                      DigitalOcean Employee badge
                                                      December 15, 2015

                                                      it says this package does not exit “import javax.servlet.annotation.MultipartConfig;”,“import javax.servlet.annotation.WebServlet; import javax.servlet.http.Part;” i m using netbeans 6.8,plz help me

                                                      - vicky

                                                        JournalDev
                                                        DigitalOcean Employee
                                                        DigitalOcean Employee badge
                                                        January 7, 2016

                                                        Hey, Very helpful code but i am not able to upload the file after choosing the file. It is throwing an error that the resource is not available. http - 404 error. Could you please help me with this

                                                        - Divya Krishna

                                                        JournalDev
                                                        DigitalOcean Employee
                                                        DigitalOcean Employee badge
                                                        March 29, 2018

                                                        So do I. I don’t understand why. I retrieve this 'useful ’ message “File uploaded successfully!”, but the file is nowhere. I used Netbeans 8, either with Tomcat or Glassfish. The file seems to be not uploaded. I used the same code here https://www.codejava.net/java-ee/servlet/java-file-upload-example-with-servlet-30-api but without result. Does it really work this code ? Did U test it ?

                                                        - udine

                                                        JournalDev
                                                        DigitalOcean Employee
                                                        DigitalOcean Employee badge
                                                        March 29, 2018

                                                        In the case where this code works, it would be very useful as we don’t need the cumbersome Apache librairies, nor the O’Reilly’s ones. In anyway thx for your work.

                                                        - udine

                                                          JournalDev
                                                          DigitalOcean Employee
                                                          DigitalOcean Employee badge
                                                          February 3, 2016

                                                          Hello Pankaj, Thanks for tutorial. This code works perfectly.But when I am trying to add this code in my existing project getting following exception during deployment in Oracle J devloper.

                                                          - rushabh

                                                          JournalDev
                                                          DigitalOcean Employee
                                                          DigitalOcean Employee badge
                                                          February 3, 2016

                                                          getting this exception Feb, 2016 10:40:56 AM IST> <Failure occurred in the execution of deployment request with ID “1454476247895” for task “0”. Error is: “weblogic.application.ModuleException: java.lang.NullPointerException” weblogic.application.ModuleException: java.lang.NullPointerException at weblogic.application.internal.ExtensibleModuleWrapper.prepare(ExtensibleModuleWrapper.java:114) at weblogic.application.internal.flow.ModuleListenerInvoker.prepare(ModuleListenerInvoker.java:100) at weblogic.application.internal.flow.ModuleStateDriver$1.next(ModuleStateDriver.java:172) at weblogic.application.internal.flow.ModuleStateDriver$1.next(ModuleStateDriver.java:167) at weblogic.application.utils.StateMachineDriver$ParallelChange.run(StateMachineDriver.java:80) Truncated. see log file for complete stacktrace Caused By: java.lang.NullPointerException at weblogic.servlet.internal.WebAnnotationProcessor.processMultipartConfigAnnotation(WebAnnotationProcessor.java:275) at weblogic.servlet.internal.AnnotationProcessingManager.processAnnotationForClasses(AnnotationProcessingManager.java:169) at weblogic.servlet.internal.AnnotationProcessingManager.processAnnotations(AnnotationProcessingManager.java:114) at weblogic.servlet.internal.AnnotationProcessingManager.processAnnotationsOutsideWebFragment(AnnotationProcessingManager.java:141) at weblogic.servlet.internal.AnnotationProcessingManager.processAnnotations(AnnotationProcessingManager.java:102) Truncated. see log file for complete stacktrace

                                                          - rushabh

                                                            JournalDev
                                                            DigitalOcean Employee
                                                            DigitalOcean Employee badge
                                                            April 7, 2016

                                                            Hi i am getting below error when i am trying to upload the file java.lang.NoSuchMethodError: javax.servlet.http.HttpServletRequest.getPart(Ljava/lang/String;)Ljavax/servlet/http/Part; com.controller.FileUploadDBServlet.doPost(FileUploadDBServlet.java:54) javax.servlet.http.HttpServlet.service(HttpServlet.java:647) javax.servlet.http.HttpServlet.service(HttpServlet.java:729) Can anyone help me on this please

                                                            - Karthik UL

                                                              JournalDev
                                                              DigitalOcean Employee
                                                              DigitalOcean Employee badge
                                                              May 21, 2016

                                                              HTTP Status 500 - GET method used with upload.UploadServlet: POST method required. type Exception report message GET method used with upload.UploadServlet: POST method required. description The server encountered an internal error that prevented it from fulfilling this request. exception javax.servlet.ServletException: GET method used with upload.UploadServlet: POST method required. upload.UploadServlet.doGet(UploadServlet.java:108) javax.servlet.http.HttpServlet.service(HttpServlet.java:621) javax.servlet.http.HttpServlet.service(HttpServlet.java:728) note The full stack trace of the root cause is available in the Apache Tomcat/7.0.37 logs.

                                                              - mansi

                                                              JournalDev
                                                              DigitalOcean Employee
                                                              DigitalOcean Employee badge
                                                              May 21, 2016

                                                              pls help with this…

                                                              - mansi

                                                                JournalDev
                                                                DigitalOcean Employee
                                                                DigitalOcean Employee badge
                                                                August 29, 2016

                                                                type Exception report message java.io.FileNotFoundException: C:\workspace\.metadata\.plugins\org.eclipse.wst.server.core\tmp0\wtpwebapps\ShopNow\images (Access is denied) description The server encountered an internal error that prevented it from fulfilling this request. exception java.io.IOException: java.io.FileNotFoundException: C:\workspace\.metadata\.plugins\org.eclipse.wst.server.core\tmp0\wtpwebapps\ShopNow\images (Access is denied) org.mz.shopnow.controller.admin.AddProductServlet.doPost(AddProductServlet.java:81) javax.servlet.http.HttpServlet.service(HttpServlet.java:647) javax.servlet.http.HttpServlet.service(HttpServlet.java:728) root cause java.io.FileNotFoundException: C:\workspace\.metadata\.plugins\org.eclipse.wst.server.core\tmp0\wtpwebapps\ShopNow\images (Access is denied) java.io.FileOutputStream.open(Native Method) java.io.FileOutputStream.(Unknown Source) java.io.FileOutputStream.(Unknown Source) org.apache.tomcat.util.http.fileupload.disk.DiskFileItem.write(DiskFileItem.java:391) org.mz.shopnow.controller.admin.AddProductServlet.doPost(AddProductServlet.java:81) javax.servlet.http.HttpServlet.service(HttpServlet.java:647) javax.servlet.http.HttpServlet.service(HttpServlet.java:728) note The full stack trace of the root cause is available in the Apache Tomcat/7.0.42 logs. Apache Tomcat/7.0.42

                                                                - ravinder singh

                                                                JournalDev
                                                                DigitalOcean Employee
                                                                DigitalOcean Employee badge
                                                                August 29, 2016

                                                                why access is denied will you please help me

                                                                - ravinder singh

                                                                  JournalDev
                                                                  DigitalOcean Employee
                                                                  DigitalOcean Employee badge
                                                                  August 29, 2016

                                                                  It clearly says file not found. Looks like you are adding server in Eclipse and using it. Try to export as WAR and deploy in a separate Tomcat server and check.

                                                                  - Pankaj

                                                                    JournalDev
                                                                    DigitalOcean Employee
                                                                    DigitalOcean Employee badge
                                                                    November 4, 2016

                                                                    Hey How to solve the FileNotFound Exception

                                                                    - Keyur

                                                                    JournalDev
                                                                    DigitalOcean Employee
                                                                    DigitalOcean Employee badge
                                                                    February 11, 2017

                                                                    I managed to fix it, the error is exactly at fileName used in part.write() function because the fileName is actually the whole path so that gives you the error. To correct the error replace from -String fullName = null; to the end of the while loop with this code: String fileName = null; //Get all the parts from request and write it to the file on server for (Part part : request.getParts()) { fileName = getFileName(part); File f = new File(fileName); part.write(uploadFilePath + File.separator + f.getName()); } Now only the name with the extension is used

                                                                    - Ahmed Ehab

                                                                      JournalDev
                                                                      DigitalOcean Employee
                                                                      DigitalOcean Employee badge
                                                                      March 2, 2017

                                                                      HTTP Status 500 - type Exception report message descriptionThe server encountered an internal error () that prevented it from fulfilling this request. exception java.io.FileNotFoundException: \D:\OnlineShoppingCenter-20170131T093840Z\OnlineShoppingCenter\build\web\productImages\cranberry-cheesecake-ck-x.jpg (The filename, directory name, or volume label syntax is incorrect) note The full stack traces of the exception and its root causes are available in the GlassFish Server Open Source Edition 3.0.1 logs. GlassFish Server Open Source Edition 3.0.1 UploadFile.java import java.io.File; import java.io.IOException; //import java.io.*; 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; @WebServlet(“/UploadFile”) @MultipartConfig(fileSizeThreshold=1024*1024*2, // 2MB maxFileSize=1024*1024*10, // 10MB maxRequestSize=1024*1024*50, location=“/”) // 50MB public class UploadFile extends HttpServlet { /** * Name of the directory where uploaded files will be saved, relative to * the web application directory. */ private static final String SAVE_DIR = “uploadFiles”; /** * handles file upload */ protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // gets absolute path of the web application String appPath = request.getServletContext().getRealPath(“”); // constructs path of the directory to save uploaded file String savePath = appPath + File.separator + SAVE_DIR; // creates the save directory if it does not exists File fileSaveDir = new File(savePath); if (!fileSaveDir.exists()) { fileSaveDir.mkdir(); } String fileName = null; for (Part part : request.getParts()) { fileName = extractFileName(part); // fileName = " “; File f = new File(fileName); part.write(savePath + File.separator + f.getName()); } request.setAttribute(“message”, fileName + “Upload has been done successfully!”); getServletContext().getRequestDispatcher(”/report-product.jsp").forward( request, response); } /** * Extracts file name from HTTP header content-disposition */ private String extractFileName(Part part) { String contentDisp = part.getHeader(“content-disposition”); String[] items = contentDisp.split(“;”); for (String s : items) { if (s.trim().startsWith(“fileName”)) { return s.substring(s.indexOf(“=”) + 2, s.length()-1); } } return “”; } } UploadProduct.java package pkg; import java.io.File; import java.io.IOException; import Model.*; import java.util.*; 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; @WebServlet(“/UploadProduct”) @MultipartConfig(fileSizeThreshold=1024*1024*10, // 10 MB maxFileSize=1024*1024*50, // 50 MB maxRequestSize=1024*1024*100,location=“/” // 100 MB ) // 50MB public class UploadProduct extends HttpServlet { private static final String SAVE_DIR = “productImages”; protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { //// Logic for Upload the File //// String appPath = request.getServletContext().getRealPath(“”); String savePath = appPath + File.separator + SAVE_DIR; File fileSaveDir = new File(savePath); if (!fileSaveDir.exists()) { fileSaveDir.mkdir(); } long unixTime = System.currentTimeMillis() / 1000L; Part part; part = request.getPart(“product_image”); String fileName = extractFileName(part); if(!fileName.equals(“”)) { fileName = extractFileName(part); File f = new File(fileName); part.write(savePath + File.separator + f.getName()); //part.write(savePath + File.separator + fileName); } else { fileName = request.getParameter(“image_name”); } //// Upload File Complete/// /////Save the Product Details ///// Product productObj = new Product(); String emp_id = “0”; if((request.getParameter(“act”)).equals(“Save”)) { HashMap results = new HashMap(); //results.put(“product_id”,request.getParameter(“product_id”)); results.put(“product_name”,request.getParameter(“product_name”)); results.put(“product_type_id”,request.getParameter(“product_type_id”)); results.put(“product_company_id”,request.getParameter(“product_company_id”)); results.put(“product_description”,request.getParameter(“product_description”)); results.put(“product_price”,request.getParameter(“product_price”)); results.put(“product_id”,request.getParameter(“product_id”)); results.put(“product_stock”,request.getParameter(“product_stock”)); results.put(“product_image”,fileName); if((request.getParameter(“product_id”)).equals(" “)) { productObj.saveProduct(results); request.setAttribute(“message”, “Product Saved Successfully !!!”); getServletContext().getRequestDispatcher(”/report-product.jsp").forward(request, response); } else { results.put(“product_id”,request.getParameter(“product_id”)); productObj.updateProduct(results); request.setAttribute(“message”, “Product Updated Successfully !!!”); getServletContext().getRequestDispatcher(“/report-product.jsp”).forward(request, response); } } } /** * Extracts file name from HTTP header content-disposition */ private String extractFileName(Part part) { String contentDisp = part.getHeader(“content-disposition”); String[] items = contentDisp.split(“;”); for (String s : items) { if (s.trim().startsWith(“filName”)) { return s.substring(s.indexOf(“=”) + 2, s.length()-1); } } return “”; } } Please help me fix this error…!!!

                                                                      - Rajitha

                                                                        JournalDev
                                                                        DigitalOcean Employee
                                                                        DigitalOcean Employee badge
                                                                        March 28, 2017

                                                                        Hi, when I make getParts() I just get an empty list. Why? I see the correct payload of my POST request like this: ------WebKitFormBoundaryh09EyJNK015Dn2QF Content-Disposition: form-data; name=“usecase” 1 ------WebKitFormBoundaryh09EyJNK015Dn2QF Content-Disposition: form-data; name=“file”; filename=“301__Ferrari__308 Gruppe 4__1980__.jpg” Content-Type: image/jpeg ------WebKitFormBoundaryh09EyJNK015Dn2QF Content-Disposition: form-data; name=“file”; filename=“302__Porsche__906__1966__.jpg” Content-Type: image/jpeg ------WebKitFormBoundaryh09EyJNK015Dn2QF–

                                                                        - bzmichi

                                                                          JournalDev
                                                                          DigitalOcean Employee
                                                                          DigitalOcean Employee badge
                                                                          October 2, 2017

                                                                          Hello, Pankaj.Following error is shown when I try to run this project. I have created a folder with the same name “uploads” under WebContent. Please help. HTTP Status 404 - /Upload_demo_Project/response.jsp type Status report message /Upload_demo_Project/response.jsp description The requested resource is not available.

                                                                          - harkirat

                                                                            JournalDev
                                                                            DigitalOcean Employee
                                                                            DigitalOcean Employee badge
                                                                            January 31, 2019

                                                                            It works so well. But when i try to upload large no of files ( size above @multipart fileSizeThreshold size) , it has be stored in a tmp dir. But it doesnt… And I’m getting this exception. Can anyone please say what can be done. work\Catalina\localhost\FileUpload\upload_92818694_fdfa_426f_9c9f_43321e273e2e_00000426.tmp file not found. Thanks in advance.

                                                                            - Jane

                                                                              JournalDev
                                                                              DigitalOcean Employee
                                                                              DigitalOcean Employee badge
                                                                              June 28, 2019

                                                                              This code work with other parameters but gives IOException at server side. Refer to my answer to get problem. https://stackoverflow.com/questions/50857699/java-io-filenotfoundexception-c-users-user-appdata-local-temp-access-is-denie/56805663#56805663

                                                                              - Navneet

                                                                                JournalDev
                                                                                DigitalOcean Employee
                                                                                DigitalOcean Employee badge
                                                                                April 6, 2020

                                                                                It Says “Cannot call sendRedirect() after the response has been committed” why is it happen sir

                                                                                - Chamindu

                                                                                  Try DigitalOcean for free

                                                                                  Click below to sign up and get $200 of credit to try our products over 60 days!

                                                                                  Sign up

                                                                                  Join the Tech Talk
                                                                                  Success! Thank you! Please check your email for further details.

                                                                                  Please complete your information!

                                                                                  Become a contributor for community

                                                                                  Get paid to write technical tutorials and select a tech-focused charity to receive a matching donation.

                                                                                  DigitalOcean Documentation

                                                                                  Full documentation for every DigitalOcean product.

                                                                                  Resources for startups and SMBs

                                                                                  The Wave has everything you need to know about building a business, from raising funding to marketing your product.

                                                                                  Get our newsletter

                                                                                  Stay up to date by signing up for DigitalOcean’s Infrastructure as a Newsletter.

                                                                                  New accounts only. By submitting your email you agree to our Privacy Policy

                                                                                  The developer cloud

                                                                                  Scale up as you grow — whether you're running one virtual machine or ten thousand.

                                                                                  Get started for free

                                                                                  Sign up and get $200 in credit for your first 60 days with DigitalOcean.*

                                                                                  *This promotional offer applies to new accounts only.