How to return an image in Spring Boot controller and serve like a file system

前端 未结 4 1396
无人及你
无人及你 2020-12-08 16:28

I\'ve tried the various ways given in Stackoverflow, maybe I missed something.

I have an Android client (whose code I can\'t change) which is currently getting an im

4条回答
  •  不知归路
    2020-12-08 17:19

    In case you don't know the file/mime type you can do this.... I've done this where i take an uploaded file and replace the file name with a guid and no extension and browsers / smart phones are able to load the image no issues. the second is to serve a file to be downloaded.

    @RestController
    @RequestMapping("img")
    public class ImageController {
    
    @GetMapping("showme")
    public ResponseEntity getImage() throws IOException{
        File img = new File("src/main/resources/static/test.jpg");
        return ResponseEntity.ok().contentType(MediaType.valueOf(FileTypeMap.getDefaultFileTypeMap().getContentType(img))).body(Files.readAllBytes(img.toPath()));
    }
    @GetMapping("thing")
    public ResponseEntity what() throws IOException{
        File file = new File("src/main/resources/static/thing.pdf");
        return ResponseEntity.ok()
                .header("Content-Disposition", "attachment; filename=" +file.getName())
                .contentType(MediaType.valueOf(FileTypeMap.getDefaultFileTypeMap().getContentType(file)))
                .body(Files.readAllBytes(file.toPath()));
    }
    
    
    }   
    

    UPDATE in java 9+ you need to add compile 'com.sun.activation:javax.activation:1.2.0' to your dependencies this has also been moved or picked up by jakarta.see this post

提交回复
热议问题