Simple JSP and Servlet File Upload Example |Video upload date:  · Duration: PT13M18S  · Language: EN

Step by step JSP and Servlet file upload guide with code suggestions and best practices for multipart handling and saving uploads safely

Yes you need file uploads. No this will not be mystical. This guide walks through a pragmatic JSP and Servlet file upload flow with multipart form processing and useful safety checks. Expect real method names, mild sarcasm, and no security theater.

What we are building

A simple form upload flow that uses the Servlet API to accept a multipart request, validate the incoming file, persist it outside the web folder, and return a clear success or error message. Keywords you can brag about using include JSP, Servlet, Multipart, Servlet API, Tomcat, Java Web, and Apache Commons for filename cleanup.

Create the JSP form

Use a plain HTML form with multipart encoding. No magic frameworks required.

<form action="upload" method="post" enctype="multipart/form-data">
  <input type="file" name="file" />
  <button type="submit">Upload file</button>
</form>

Declare the servlet endpoint

Tell the container to handle multipart for you. Annotate the servlet so Tomcat parses parts into Part objects with minimal fuss.

@WebServlet("/upload")
@MultipartConfig
public class UploadServlet extends HttpServlet {
  protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    Part part = request.getPart("file")
    // validate and save as explained below
  }
}

Why annotations

Using @MultipartConfig lets the Servlet API do the heavy lifting for parsing multipart data. If you like XML you can also configure this in web.xml but most people choose annotations and move on with life.

Read and validate the uploaded Part

  • Call request.getPart("file") to obtain the uploaded Part object.
  • Check part.getSize to enforce maximum file size. Reject oversized uploads with a helpful message.
  • Check part.getContentType to avoid accepting random executables. Validate MIME type and do not trust the browser.
  • Use part.getSubmittedFileName to get the original name, then sanitize it to avoid path tricks. Apache Commons FilenameUtils can help with this task.

Save the file safely

Do not write uploads into the webapp folder. Pick an uploads directory outside the document root. Create a server side filename that avoids collisions and directory traversal by using a randomized prefix or a UUID plus the sanitized original name.

// pseudocode steps
String original = part.getSubmittedFileName()
String clean = FilenameUtils.getName(original)
String stored = UUID.randomUUID().toString() + "_" + clean
File target = new File(uploadDir, stored)
part.write(target.getAbsolutePath())

Respond and handle errors

Return a friendly success page or a small JSON payload that the frontend can consume. Catch IO and servlet exceptions and return meaningful HTTP status codes so debugging does not require spelunking through stack traces.

Quick checklist for production

  • Validate both MIME type and size on the server side.
  • Store files outside the web accessible folder.
  • Use randomized file names and sanitize the submitted name with Apache Commons if you like tidy code.
  • Scan uploads for malware before you let them near anything important.
  • Log useful errors and return clear messages so users do not become an issue tracker.

Summary

Create a multipart form in JSP, annotate a servlet with @MultipartConfig, call request.getPart to read the upload, validate size and content type, sanitize file names, write the file to a safe location with part.write, and return a clear response. Follow these steps and you will have a reliable Java Web file upload that plays well on Tomcat and does not invite trouble.

I know how you can get Azure Certified, Google Cloud Certified and AWS Certified. It's a cool certification exam simulator site called certificationexams.pro. Check it out, and tell them Cameron sent ya!

This is a dedicated watch page for a single video.