Blog Image

FileUpload  

This blog explains about how to upload the file using servlets and what are the methods we are using for uploading the file when Uploading time what are the restrictions we need to follow for uploading file.

UploadFile :

When the file is selected, it is sent to the server as a part of a POST request. During this process two mandatory restrictions are applied to the form with input type file:

  • The enctype attribute must be set to a value of multipart/form-data.
  • Its method must be POST.

Upload.jsp:
<body>
<center>
    <h1>File Upload</h1>
    <form method="post" action="UploadFile"
        enctype="multipart/form-data">
        Select file to upload: <input type="file" name="file" size="60" /><br />
        <br /> <input type="submit" value="UploadFile" />
    </form>
</center>
</body>


Success.jsp:
<title>File Upload Success</title>
</head>
<body>
    <h2>${requestScope.message}</h2>
</body>

Methods:
 Part(interface): represents a part in a multipart/form-data request. This interface defines some methods for working with upload data :
  • write(String filename): this is the convenient method to save upload data to file on disk.
  • getParts(): it returns collection of Part objects
  • getPart : retrieves an individual Part object with a given name.

If you want to restrict the file size use below one, @MultipartConfig(fileSizeThreshold=1024*1024*2,maxFileSize=1024*1024*10,maxRequestSize=1024*1024*50)
UploadServlet.jsp
See the below example for uploading file using servlet:

@WebServlet("/UploadFile")
@MultipartConfig
public class UploadServelet extends HttpServlet {

    private static final long serialVersionUID = 1L;

    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {

        // file saving location
        String savePath = "E:/Files";

        for (Part part : request.getParts()) {
            String fileName = extractFileName(part);
            part.write(savePath + fileName);
        }

        request.setAttribute("message", "Your file is uploaded successfully!");
        getServletContext().getRequestDispatcher("/success.jsp").forward(request, response);
    }

    /**
     * for Extracting the file name
     */
    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 "";
    }
}

When we are uploading the file , that file include content-disposition header .
Extracting filename purpose we are using extractFileName() method.it will get the actual fileName.


Attachments

About author

User Image
sagarreddy

my self is SagarReddy. I from bhadrachalam and i am working StackSpace software solutions pvt. Ltd. has a java developer. Learning the new things from authors to update my self to build my career Better Way.

1

-Comments

Be the first person to write a comment for this Blog
  • author image
    by:
      MaheswaraD
      17-12-2017 07:13:07 AM

    very nice blog sagarreddy. thanks to write such a nice blog and sharing your knowledge with us.

Load More

No More Comments

Leave a Comment

Your comment has been posted and will appear soon.