pom.xml
<dependency> <groupId>commons-fileupload</groupId> <artifactId>commons-fileupload</artifactId> <version>1.4</version> </dependency>
java file
import java.io.File;
import java.io.IOException;
import java.util.List;
import java.util.stream.Collectors;
import javax.servlet.ServletException;
import javax.servlet.annotation.MultipartConfig;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.Part;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
public class FileUploadServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
try {
List<Part> fileParts = request.getParts().stream().filter(part -> "file".equals(part.getName()))
.collect(Collectors.toList());
for (Part filePart : fileParts) {
String fileName = filePart.getSubmittedFileName();
String uploadPath = getServletContext().getRealPath("") + File.separator + "uploads" + File.separator
+ fileName;
// Save the file
filePart.write(uploadPath);
}
response.getWriter().println("File upload successful!");
} catch (Exception e) {
response.getWriter().println("File upload failed due to: " + e.getMessage());
}
}
}
html
<html> <head> <title>File Upload Example</title> </head> <body> <form action="fileUpload" method="post" enctype="multipart/form-data"> Select a file to upload: <input type="file" name="file"><br> <input type="submit" value="Upload"> </form> </body> </html>
Make sure to configure the @MultipartConfig
annotation appropriately based on your application's needs.
Remember to handle exceptions and validations based on your specific requirements in a production environment. This example provides a basic setup for handling file uploads using Apache Commons FileUpload with a servlet in a Java web application.