2012-10-29 75 views
6

我是新來的春天。我有一個控制器與一個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 
} 

感謝

+4

見回答: http://stackoverflow.com/questions/5673260/downloading-a- file-from-spring-controllers –

+0

這是哪種類型的文件? –

回答

12

感謝@ JAR.JAR.beans。這裏是鏈接: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)); 
} 
6

可能,這將有助於

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

的另一種方式,雖然Jatin's answer是遠遠冷卻器:

1

這就像一個魅力對我來說:這裏

@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; 
     } 
    } 
相關問題