I'm using Spark java with below dependency, and I'm trying to make one API endpoint to receive an file using multipart file, Below is the code attached, I've tried multiple ways to do that, but everytime I'm getting request.raw().getPart("file") as null. Please correct me where I'm going wrong.
com.sparkjava.spark-core.2.9.4
public class FileUploadRoutesNew {
public void registerRoutes() {
post("/upload/new", "multipart/form-data", (request, response) -> {
// Enable multipart support
String location = "/tmp"; // the directory location where files will be stored
long maxFileSize = 100000000; // the maximum size allowed for uploaded files
long maxRequestSize = 100000000; // the maximum size allowed for multipart/form-data requests
int fileSizeThreshold = 1024; // the size threshold after which files will be written to disk
MultipartConfigElement multipartConfigElement = new MultipartConfigElement(
location, maxFileSize, maxRequestSize, fileSizeThreshold);
request.raw().setAttribute("org.eclipse.jetty.multipartConfig",
multipartConfigElement);
Collection<Part> parts = request.raw().getParts();
for (Part part : parts) {
System.out.println("Name: " + part.getName());
System.out.println("Size: " + part.getSize());
System.out.println("Filename: " + part.getSubmittedFileName());
}
try {
Part filePart = request.raw().getPart("file_upload"); // "file" is the form field name
String fileName = filePart.getSubmittedFileName();
File uploadDir = new File("uploads");
uploadDir.mkdirs(); // Create the directory if not exists
File uploadedFile = new File(uploadDir, fileName);
try (InputStream is = filePart.getInputStream();
OutputStream os = new FileOutputStream(uploadedFile)) {
IOUtils.copy(is, os);
}
filePart.delete(); // Clean up temp file
response.status(200);
return "File uploaded successfully: " + fileName;
} catch (Exception e) {
e.printStackTrace();
response.status(500);
return "File upload failed: " + e.getMessage();
}
});
}
}