Skip to content
Sandny Blog
  • Home
  • Java
  • JavaScript
  • AWS
  • Embedded
  • About
Servlet File Upload Java

Servlet File Upload

  • May 18, 2017July 26, 2021
  • by Coder Kai

HOW TO UPLOAD FILES AND EXTRACT OTHER DATA FROM A POST SUBMISSION IN A SERVLET

In working with java EE, the submission of data from a JSP or a Servlet is basically handled by Struts or Spring frameworks. But for programmers, who may have an interest in the things in a POST Request, will find some use in this. Especially, if you intend to build a separate framework for any web application.

 

First of all, make a JSP page with a form consisting two input fields and a file field.

<form action="UploadInfo" method="POST" enctype="multipart/form-data"> 
    <label>NAME</label><input type="text" name="cust_name" /><br /> 
    <label>TELEPHONE</label><input type="text" name="cust_tel" /><br /> 
    <label>PICTURE</label><input type="file" name="cust_pic" /><br /> 
    <input type="submit" value="ADD" /><br /> 
</form>

 

Please don’t bother CSS and other decorations, coz I haven’t used any. Now I’m going to code the servlet for the upload action

ABOUT THE CODE

The code will go inside protected void doPost(HttpServletRequest request, HttpServletResponse response) method of the UploadInfo Servlet. We have to be certain whether the request has a file to upload in the first place. If not, there will be no confusion in retrieving the String data from the POST request.

protected void doPost(HttpServletRequest request, HttpServletResponse response) 
            throws ServletException, IOException { 
        response.setContentType("text/html;charset=ISO-8859-1"); 
        PrintWriter out = response.getWriter(); 
        try { 
            String contentType = request.getContentType(); 
            String imageLocation =""; 
            String imageName=""; 
            String name=""; 
            String tel=""; 
            if ((contentType != null) && (contentType.indexOf("multipart/form-data") >= 0)) { 
 
                DataInputStream in = new DataInputStream(request.getInputStream()); 
                int formDataLength = request.getContentLength(); 
                byte dataBytes[] = new byte[formDataLength]; 
                int byteRead = 0; 
                int totalBytesRead = 0; 
                while (totalBytesRead < formDataLength) { 
                    byteRead = in.read(dataBytes, totalBytesRead, formDataLength); 
                    totalBytesRead += byteRead; 
                } 
                String file = new String(dataBytes); 
 
                String saveFile = file.substring(file.indexOf("filename=\"") + 10); 
                saveFile = saveFile.substring(0, saveFile.indexOf("\n")); 
                saveFile = saveFile.substring(saveFile.lastIndexOf("\\") + 1, saveFile.indexOf("\"")); 
 
                int lastIndex = contentType.lastIndexOf("="); 
                String boundary = contentType.substring(lastIndex + 1, contentType.length()); 
                int pos; 
                pos = file.indexOf("filename=\""); 
                pos = file.indexOf("\n", pos) + 1; 
                pos = file.indexOf("\n", pos) + 1; 
                pos = file.indexOf("\n", pos) + 1; 
 
                imageName = "hello" + saveFile.substring(saveFile.length() - 4); 
 
                imageLocation = getServletContext().getRealPath("")+ "\\images\\" + imageName; 
 
                int boundaryLocation = file.indexOf(boundary, pos) - 4; 
                int startPos = ((file.substring(0, pos)).getBytes()).length; 
                int endPos = ((file.substring(0, boundaryLocation)).getBytes()).length; 
                File f = new File(imageLocation); 
 
                FileOutputStream fileOut = new FileOutputStream(f); 
                fileOut.write(dataBytes, startPos, (endPos - startPos)); 
                fileOut.flush(); 
                fileOut.close(); 
                /** 
                 * Retrieves other fields in the POST request 
                 */ 
                name=retrieveName(file, "cust_name"); 
                tel=retrieveName(file, "cust_tel"); 
 
            } 
            out.println("<html>"); 
            out.println("<head>"); 
            out.println("<title>Servlet UploadInfo</title>"); 
            out.println("</head>"); 
            out.println("<body>"); 
            out.println("<p>Name : " + name + "<br> Tel : " + tel + "</p>"); 
            out.println("<img src=\"" +imageName + "\" />"); 
            out.println("</body>"); 
            out.println("</html>"); 
        } finally { 
            out.close(); 
        } 
    } 
 
    private String retrieveName(String file, String name) { 
        String[] split = file.split("\"" + name + "\""); 
        if (split.length >= 2) { 
            return split[1].toString().substring(0, split[1].indexOf("------")).trim(); 
        } else { 
            return null; 
        } 
    }

 

WHAT I DID
String contentType = request.getContentType(); 
if ((contentType != null) && (contentType.indexOf("multipart/form-data") >= 0)) { }

This will check whether request has any content type and it has some file format in it. Now, you can code DataStream works inside those braces.

DataInputStream in = new DataInputStream(request.getInputStream()); 
             int formDataLength = request.getContentLength(); 
             byte dataBytes[] = new byte[formDataLength]; 
             int byteRead = 0; 
             int totalBytesRead = 0; 
             while (totalBytesRead < formDataLength) { 
                 byteRead = in.read(dataBytes, totalBytesRead, formDataLength); 
                 totalBytesRead += byteRead; 
             } 
             String file = new String(dataBytes);

 

Above code is to take the stream to a String.

String saveFile = file.substring(file.indexOf("filename=\"") + 10); 
                saveFile = saveFile.substring(0, saveFile.indexOf("\n")); 
                saveFile = saveFile.substring(saveFile.lastIndexOf("\\") + 1, saveFile.indexOf("\""));

 

Above is to get the file name.

                int lastIndex = contentType.lastIndexOf("="); 
                String boundary = contentType.substring(lastIndex + 1, contentType.length()); 
                int pos; 
                pos = file.indexOf("filename=\""); 
                pos = file.indexOf("\n", pos) + 1; 
                pos = file.indexOf("\n", pos) + 1; 
                pos = file.indexOf("\n", pos) + 1; 
 
                String imageName = "hello" + saveFile.substring(saveFile.length() - 4); 
 
                 String imageLocation = getServletContext().getRealPath("") 
                        + "\\" + imageName; 
 
                int boundaryLocation = file.indexOf(boundary, pos) - 4; 
                int startPos = ((file.substring(0, pos)).getBytes()).length; 
                int endPos = ((file.substring(0, boundaryLocation)).getBytes()).length;

 

Above is to get the position of the image data correctly. You can understand the above code if you JUST PRINT the file String in the response.

                File f = new File(imageLocation); 
 
                FileOutputStream fileOut = new FileOutputStream(f); 
                fileOut.write(dataBytes, startPos, (endPos - startPos)); 
                fileOut.flush(); 
                fileOut.close();

 

Above is to get the position of the image data correctly. You can understand the above code if you JUST PRINT the file String in the response.

  private String retrieveName(String file, String name) { 
        String[] split = file.split("\"" + name + "\""); 
        if (split.length >= 2) { 
            return split[1].toString().substring(0, split[1].indexOf("------")).trim(); 
        } else { 
            return null; 
        } 
    }

 

Above method is to retrieve cust_name and the cust_tel field from the POST submission as getParameter(String name) won’t work.

RESULT
JAVA RMI Observer Slider
Kubuntu 15.04 KDE with Plasma 5.3
Coder Kai
A humble developer

Related articles

String.lines()
How to convert a string…
How to avoid NullPointerException in Java
How to avoid NullPointerException in…
The new features in Java 14
JDK 14 – The new…
Java 13 features
Java 13 (JDK 13) -The…
Java 13 Switch Expressions
How to enable preview feature in Java 13 with maven.
Enable the Preview Feature in…
create a Vertx Eventbus js client
How to create a Vertx…
neo4j boltdriver
How to create a neo4j…
Java RMI Slider
JAVA RMI Observer Slider

Categories

  • android 3
  • Apollo Client 1
  • AWS 8
    • AppSync 5
    • EC2 1
    • EKS 1
    • Route53 1
    • S3 1
  • AWS Amplify 1
  • Chakra UI 1
  • Docker 1
  • Embedded 1
  • EmberJS 1
  • FCM 1
  • Godaddy 1
  • GraphQL 3
  • ios 1
  • Jasper 1
  • Java 10
    • Java 11 1
    • Java 14 1
  • JavaEE 2
  • JavaScript 39
    • Express.js 4
    • Javascript Guide 7
    • Node.js 3
    • react-native 4
    • React.js 17
    • Typescript 1
  • Kubernetes 1
  • machine learning 1
  • Maven 2
  • OCaml 3
  • PostgreSQL 1
  • Python 2
  • react-native 4
  • ReactJS 3
  • sass 1
  • Server 6
  • spark 1
  • Terraform 2
  • Ubuntu 4
  • Uncategorized 1
  • webpack 2

Recent Comments

  • pagerank seo buyhacklink.com on How to create Lambda function with Terraform
  • uMsNeies on How to create a neo4j BoltDriver Datasource and connect it with a web app
  • binance註冊 on Java 13 Switch Expressions

Meta

  • Log in
  • Entries feed
  • Comments feed
  • WordPress.org

Archives

  • October 2022 3
  • September 2022 7
  • May 2022 1
  • December 2021 1
  • August 2021 1
  • July 2021 6
  • June 2021 3
  • February 2021 1
  • July 2020 1
  • December 2019 5
  • November 2019 6
  • October 2019 3
  • August 2019 1
  • March 2019 1
  • February 2019 1
  • January 2019 2
  • December 2018 1
  • September 2018 2
  • August 2018 1
  • June 2018 1
  • February 2018 1
  • November 2017 2
  • October 2017 5
  • September 2017 1
  • June 2017 1
  • May 2017 10
Sandny Blog space
Theme by Colorlib Powered by WordPress