Jatin
Jatin

Reputation: 31724

Return a file from Controller in Spring

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

Upvotes: 18

Views: 49781

Answers (5)

Vikash Kumar
Vikash Kumar

Reputation: 1216

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

Upvotes: 0

Andrii Dobrianskiy
Andrii Dobrianskiy

Reputation: 21

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;
        }
    }

Upvotes: 1

Jatin
Jatin

Reputation: 31724

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)); 
}

Upvotes: 19

Allenaz
Allenaz

Reputation: 1109

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:

Upvotes: 2

shazinltc
shazinltc

Reputation: 3666

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
    }
}

Upvotes: 8

Related Questions