<tutorialjinni.com/>

Upload File to Server Using Java Servlet

Posted Under: HTML5, JAVA, Programming, Tutorials on Mar 3, 2017
File upload is trivial to any web application. Prior to Java Servlet specification 3.0 upload to server required Apache Commons. Now its just a matter of writing a just any other file. Fist you need a HTML or JSP page with the form with file filed as follows
<html>
<head>
<title>Upload File in Servlet Java EE | Tutorial Jinni</title>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<style>input,label{font-size:2em}body{background:#445446;display:flex;justify-content:center;align-items:center;margin-top:250px;font-family:cursive}input{border:#000;padding:10px;width:100%;border-radius:5px}label{display:block;color:#fff;margin:0 0 4px}#absoluteCenteredDiv{position:absolute;top:0;bottom:0;left:0;right:0;margin:auto;width:500px;height:300px;text-align:center}</style>
</head>
<body>
<div id="absoluteCenteredDiv">
    <form action="FileUploadServlet" method="post" enctype="multipart/form-data">
	<label for="file">Select File To Upload</label>
	<input type="file" name="file" />
	<input type="submit" name="Upload File" />
    </form>
</div>
</body>
</html>
Notice, following attributes are required in HTML Form to upload a file. Uploading Server must be annotated with @MultipartConfig other wise it will not work.
method="post" enctype="multipart/form-data"
On the server side copy the following code
import java.io.*;
import java.nio.file.Paths;
import javax.servlet.ServletException;
import javax.servlet.annotation.MultipartConfig;
import javax.servlet.http.*;

/**
 *
 * @author BX650CI
 */

@MultipartConfig

public class FileUploadServlet extends HttpServlet {
    
    protected void processRequest(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        response.setContentType("text/html;charset=UTF-8");
        try {
            PrintWriter out = response.getWriter();
                try{
                Part filePart = request.getPart("file");
                String fileName = Paths.get(filePart.getSubmittedFileName()).getFileName().toString();
                InputStream fileContent = filePart.getInputStream();
                
                String uploadDirectory="PATH_UPLOAD_DIR"; // Change it
                
                File f=new File(uploadDirectory+fileName);
                OutputStream outStream=new FileOutputStream(f);
                int read = 0;
                byte[] bytes = new byte[1024];
                while ((read = fileContent.read(bytes)) != -1) {
                    outStream.write(bytes, 0, read);
                }
                out.print("File Uploaded Successfully at : "+f.toURI());
            }
            catch(Exception ex){
                out.print("Problem in File Upload"+ex.toString());
            }
        }
        catch(Exception ex){
            // log servlet issues using log4j 
            // or write exception to File
        }
    }

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }

    @Override
    public String getServletInfo() {
        return "Short description";
    }
}

Caution for File Uploading

  • Scan file for viruses using an anti-virus. If you do not have one use Virus Toral API. Read more on how to Scan uploaded file using Virus Total Free Public API
  • Implement a file size check.
  • Never save the uploaded file with user provided name.
  • Never stream file to user directly from upload directory.
  • Save file outside of document or web root.


imgae