March 28, 2024
How to upload Images from rest API in Spring boot
TechTechInfo.com » How to upload Images from rest API in Spring boot

How to upload Images from rest API in Spring boot

upload imge in spring boot rest api
upload imge in spring boot rest api

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();
Java

Create a FileOutputSteam object to get the original file name

FileOutputStream fos = new FileOutputStream(originalFilename)
Java

Now write the file with the same name from the mutipartFile file

fos.write(multipartFile.getBytes());
Java

After 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

upload imge in spring boot rest api
upload imge in spring boot rest api

Now test the upload doc API from the postman,

test upload doc api in postman
test upload doc api in 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();
Java

You 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
Join the discussion

Translate »