I’m learning SpringBoot and running into an issue when uploading images to MySQL database. Getting a NoSuchFileException when I try to save images through Swagger UI. Not sure what’s causing this problem.
My Entity:
@Lob
@Basic(fetch = FetchType.LAZY)
@Column(name = "photo_data")
private byte[] photoData;
Service Method:
public ProductInfo saveProduct(ProductInfo product, MultipartFile imageFile) throws IOException {
if (product.getProductName() == null || product.getProductName().isEmpty()
|| product.getBrandName() == null || product.getBrandName().isEmpty()
|| product.getDescription() == null || product.getDescription().isEmpty()
|| product.getPrice() == null || product.getPrice() < 0) {
throw new BadRequestException("Missing required product details.");
}
product.setPhotoData(imageFile.getBytes());
productRepository.save(product);
return product;
}
Controller:
@PostMapping(value = "/saveProduct", consumes = MediaType.MULTIPART_FORM_DATA_VALUE)
public ResponseEntity<ProductInfo> saveProduct(@ModelAttribute ProductInfo product,
@RequestParam("imageFile") MultipartFile imageFile) throws IOException {
ProductInfo result = productService.saveProduct(product, imageFile);
return new ResponseEntity<>(result, HttpStatus.CREATED);
}
Tried different approaches but nothing works. Any ideas what might be wrong?
i think it might be due to how swagger handles file uploads. try adding a null check before calling getBytes(), like if(imageFile != null && !imageFile.isEmpty()). also, make sure your swagger setup is configured to allow multipart uploads.
Had this exact issue last year building a product catalog app. Spring Boot’s multipart resolver creates temp files that get deleted before your service method can process them. Here’s what fixed it for me: add these to application.properties: spring.servlet.multipart.max-file-size=10MB and spring.servlet.multipart.max-request-size=10MB. Make sure your temp directory has write permissions. If you’re using containers, check that temp directories are mounted correctly. NoSuchFileException usually means the temp file got cleaned up too early or couldn’t be created due to permissions.
check if the temp folder exists and is writable. sometimes, the multipart resolver can’t create temp files, leading to this error. also, consider making the imageFile param optional for debugging: @RequestParam(value = "imageFile", required = false).
NoSuchFileException happens when Spring cleans up the temp file before you can access it. Usually there’s a delay in processing or you’re not handling the file immediately. Wrap your file processing in try-catch and call imageFile.getBytes() right after getting the request. Check your application.properties too - set spring.servlet.multipart.location to a valid temp directory path. I’ve seen this when the default temp directory wasn’t accessible or had permission issues.