在Spring中从Controller返回一个文件

Jat*_*tin 9 spring spring-mvc

我是新来的春天.我有一个带有RequestMapping的控制器,用于多个GET参数.他们返回一个字符串.但是一种方法需要在"/ res /"文件夹中返回一个文件.我怎么做?

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

谢谢

Jat*_*tin 14

感谢@ JAR.JAR.beans.这是链接:从弹簧控制器下载文件

@RequestMapping(value = "/files/{file_name}", method = RequestMethod.GET)
@ResponseBody 
public FileSystemResource getFile(@PathVariable("file_name") String fileName) {
    return new FileSystemResource(myService.getFileFor(fileName)); 
}
Run Code Online (Sandbox Code Playgroud)


sha*_*ltc 7

可能这会有所帮助

@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
    }
}
Run Code Online (Sandbox Code Playgroud)