W3docs

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:

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">
</form>
  1. In your Servlet, add the @MultipartConfig annotation to enable multipart request parsing. You will also need to import the necessary classes and extend HttpServlet.

import java.io.*;
import javax.servlet.annotation.*;
import javax.servlet.http.*;

@WebServlet("/upload")
@MultipartConfig
public class FileUploadServlet extends HttpServlet {
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) 
            throws ServletException, IOException {
        // Steps 3-5 go here
    }
}
  1. Inside the doPost method, 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. Note that getSubmittedFileName() already returns the clean filename without the client's path, so the Paths manipulation is unnecessary.

String fileName = filePart.getSubmittedFileName();
  1. Use the getInputStream method of the Part object to get an InputStream for reading the file data, then write it to the server's file system:

InputStream fileContent = filePart.getInputStream();
String uploadPath = getServletContext().getRealPath("") + File.separator + "uploads";
File uploadDir = new File(uploadPath);
if (!uploadDir.exists()) {
    uploadDir.mkdir();
}
File file = new File(uploadPath + File.separator + fileName);
OutputStream out = new FileOutputStream(file);
byte[] buffer = new byte[1024];
int length;
while ((length = fileContent.read(buffer)) > 0) {
    out.write(buffer, 0, length);
}
out.close();
fileContent.close();

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.