Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 251
Jatin Avatar asked Oct 29 '12 10:10

Jatin


1 Answers

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
    }
}
like image 170
shazinltc Avatar answered Dec 22 '22 06:12

shazinltc