Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Spring boot - Grabbing a file from the file system in a Get Request

I am trying to grab a file (in this case an image) from the file system and display it. I can do it from a resources subdirectory just fine, but when I try to go to the file system it is giving me a FileNotFound exception.

java.io.FileNotFoundException: file:\Y:\Kevin\downloads\pic_mountain.jpg (The filename, directory name, or volume label syntax is incorrect)

All the rest of my code is vanilla spring boot that was generated from the Initialize. Thanks.

@RestController
public class ImageProducerController {

    @GetMapping("/get-text")
    public @ResponseBody String getText() {
        return "Hello World";
    }

    @GetMapping(value = "/get-jpg", produces = MediaType.IMAGE_JPEG_VALUE)
    public void getImage(HttpServletResponse response) throws IOException {

        FileSystemResource imgFile = new FileSystemResource("file:///Y:/Kevin/downloads/pic_mountain.jpg");
//        ClassPathResource imgFile = new ClassPathResource("images/pic_mountain.jpg");
        System.out.println(imgFile.getURL());
        response.setContentType(MediaType.IMAGE_JPEG_VALUE);
        StreamUtils.copy(imgFile.getInputStream(), response.getOutputStream());
    }
}
like image 889
kjbeamer Avatar asked Aug 27 '17 18:08

kjbeamer


People also ask

How do I transfer files using spring boot?

Spring Boot file uploader Create a Spring @Controller class; Add a method to the controller class which takes Spring's MultipartFile as an argument; Save the uploaded file to a directory on the server; and. Send a response code to the client indicating the Spring file upload was successful.

How do you send a multipart file in request body?

To pass the Json and Multipart in the POST method we need to mention our content type in the consume part. And we need to pass the given parameter as User and Multipart file. Here, make sure we can pass only String + file not POJO + file. Then convert the String to Json using ObjectMapper in Service layer.


1 Answers

from the docs:

public FileSystemResource(String path)
Create a new FileSystemResource from a file path

the constructor expects a path-part of the url, so in your case only Y:/Kevin/downloads/pic_mountain.jpg

so you should try to use it this way:

FileSystemResource imgFile = new FileSystemResource("Y:/Kevin/downloads/pic_mountain.jpg");

Btw. could it be, that you miss "Users" in your path? -> Y:/Users/Kevin/downloads/pic_mountain.jpg

like image 85
JohnnyAW Avatar answered Sep 28 '22 15:09

JohnnyAW