How can I upload files to a server using JSP/Servlet?

To upload files to a server using JSP/Servlet, you can use the following steps:

  1. Create an HTML form for the file upload with the enctype attribute set to "multipart/form-data". This will allow the form to submit file data to the server.
<form action="/upload" method="post" enctype="multipart/form-data">
  <input type="file" name="file">
  <input type="submit" value="Upload">
  1. In your JSP/Servlet, use the request.getPart method to get the Part object representing the uploaded file.
Part filePart = request.getPart("file");
  1. Use the getSubmittedFileName method of the Part object to get the file name of the uploaded file.
String fileName = Paths.get(filePart.getSubmittedFileName()).getFileName().toString();  // MSIE fix
  1. Use the getInputStream method of the Part object to get an InputStream for reading the file data.
InputStream fileContent = filePart.getInputStream();
  1. Use the InputStream to read the file data and write it to the desired location on the server. You can use the OutputStream of a FileOutputStream to write the file data to the server's file system, for example:
String uploadPath = getServletContext().getRealPath("") + File.separator + UPLOAD_DIR;
File uploadDir = new File(uploadPath);
if (!uploadDir.exists()) {
File file = new File(uploadPath + File.separator + fileName);
OutputStream out = new FileOutputStream(file);
byte[] buffer = new byte[1024];
int length;
while ((length = > 0) {
    out.write(buffer, 0, length);

This will read the file data from the InputStream in 1024-byte chunks and write it to the specified file on the server.

Note that this is just a basic example, and you may need to handle other issues such as file size limits, file type validation, and error handling in your actual implementation.