Hello Everyone, If you want to upload the image from the rest api in the sprint boot application then first we have to setup the spring boot application first install the postman for the testing of the api.
Below are the steps to upload the document
Get the original file name from the multipart file
String originalFilename = multipartFile.getOriginalFilename();
JavaCreate a FileOutputSteam object to get the original file name
FileOutputStream fos = new FileOutputStream(originalFilename)
JavaNow write the file with the same name from the mutipartFile file
fos.write(multipartFile.getBytes());
JavaAfter creating the new file we can delete this file also
originalFilename.delete();
These are the important steps to upload an image through Spring boot rest API
Now let’s implement the above code in a rest API “api/uploadDoc”
Create a rest Controller with the name CommonController.java
Now test the upload doc API from the postman,
To delete the uploaded file in Spring boot
First, we have to create a file object with the same file name and file path. Then you can delete the image from the uploaded path.
File file = new File(originalFilename);
file.delete();
JavaYou can copy the content of the testController given below.
@Slf4j
@RestController
@RequestMapping("api/v1")
public class TectController {
@PostMapping(path = "uploadDoc")
public String uploadImageToS3(@RequestParam("file") MultipartFile multipartFile, HttpServletRequest header) throws IOException {
try {
String originalFilename = multipartFile.getOriginalFilename();
File file = new File(originalFilename);
try (FileOutputStream fos = new FileOutputStream(originalFilename)) {
fos.write(multipartFile.getBytes());
} catch (IOException e) {
throw new IOException("Failed to convert multipart file to file", e);
}
file.delete();
return "File uploaded successfully";
} catch (Exception e) {
// TODO: handle exception
log.error("Error :: {}", e.getLocalizedMessage());
return "Something went wrong";
}
}
}
Java