18

I am new to spring. I have a controller with a RequestMapping for several GET parameters. They return a String . But one method needs to return a file in the "/res/" folder. How do I do that?

@RequestMapping(method = RequestMethod.GET,value = "/getfile")
public @ResponseBody 
String getReviewedFile(@RequestParam("fileName") String fileName)
{
    return //the File Content or better the file itself
}

Thanks

Jatin
  • 31,116
  • 15
  • 98
  • 163

5 Answers5

16

Thanks to @JAR.JAR.beans. Here is the link: Downloading a file from spring controllers

@RequestMapping(value = "/files/{file_name}", method = RequestMethod.GET)
@ResponseBody 
public FileSystemResource getFile(@PathVariable("file_name") String fileName) {
    return new FileSystemResource(myService.getFileFor(fileName)); 
}
Community
  • 1
  • 1
Jatin
  • 31,116
  • 15
  • 98
  • 163
  • 1
    In addition to this, you can also return a file with dynamically generated content. You will need to return byte[] in ResponseEntity with appropriate headers to do that. Here is an example: https://allaboutspringframework.com/java-spring-download-file-from-controller/ – Muhammad Asher Toqeer Mar 29 '21 at 13:47
8

May be this will help

@RequestMapping(method = RequestMethod.GET,value = "/getfile")
public @ResponseBody 
void getReviewedFile(HttpServletRequest request, HttpServletResponse response, @RequestParam("fileName") String fileName)
{
    //do other stuff
    byte[] file = //get your file from the location and convert it to bytes
    response.reset();
    response.setBufferSize(DEFAULT_BUFFER_SIZE);
    response.setContentType("image/png"); //or whatever file type you want to send. 
    try {
        response.getOutputStream().write(image);
    } catch (IOException e) {
        // Do something
    }
}
Walery Strauch
  • 6,792
  • 8
  • 50
  • 57
shazinltc
  • 3,616
  • 7
  • 34
  • 49
2

Another way, though Jatin's answer is way cooler :

//Created inside the "scope" of @ComponentScan
@Configuration
public class AppConfig extends WebMvcConfigurerAdapter {
    @Value("${files.dir}")
    private String filesDir;

    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        registry
                .addResourceHandler("/files/**")
                .addResourceLocations("file:" + filesDir);
    }
}

Lifted from:

Community
  • 1
  • 1
Allenaz
  • 1,013
  • 10
  • 14
  • OK, what if I want `https://my-site.com/prefix/to/remove/file.png` to return `/images/file.png`? What should I write in `addResourceHandler` to specify that `/prefix/to/remove` parth must be removed? So far I see that Spring tries to find `/images/prefix/to/remove/file.png` instead of `/images/file.png`. – izogfif Sep 10 '20 at 13:22
1

This works like a charm for me:

@RequestMapping(value="/image/{imageId}", method = RequestMethod.GET)
    public ResponseEntity<byte[]> getImage(@PathVariable String imageId) {
        RandomAccessFile f = null;
        try {
            f = new RandomAccessFile(configs.getImagePath(imageId), "r");
            byte[] b = new byte[(int)f.length()];
            f.readFully(b);
            f.close();
            final HttpHeaders headers = new HttpHeaders();
            headers.setContentType(MediaType.IMAGE_PNG);
            return  new ResponseEntity<byte[]>(b, headers, HttpStatus.CREATED);
        } catch (Exception e) {
            return null;
        }
    }
0

If you are working on local Windows machine this could be useful for you:

@RequestMapping(value="/getImage", method = RequestMethod.GET)
    @ResponseBody
    public FileSystemResource getUserFile(HttpServletResponse response){

        final File file = new File("D:\\image\\img1.jpg");

        response.reset();
        response.setContentType("image/jpeg");


        return new FileSystemResource(file);
    }

for testing your code you can use Postman "Use Send And Download not just send"

Another Approach to return byte:

@GetMapping("/getAppImg")
    @ResponseBody
    public byte[] getImage() throws IOException {

        File serveFile = new File("image_path\\img.jpg");

        return Files.readAllBytes(serveFile.toPath());
    }
Vikash Kumar
  • 1,096
  • 11
  • 10