2012-10-29 13 views
6

Jestem nowy na wiosnę. Mam kontroler z ApplicationMapping dla kilku parametrów GET. Zwracają String. Ale jedna metoda musi zwrócić plik w folderze "/ res /". Jak mogę to zrobić?Zwróć plik z kontrolera na wiosnę

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

Dzięki

+4

Patrz odpowiedź tutaj: http://stackoverflow.com/questions/5673260/downloading-a- file-from-spring-controllers –

+0

Jaki to jest plik? –

Odpowiedz

12

Dzięki @ JAR.JAR.beans. Oto 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)); 
} 
6

Może to pomoże

@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

inny sposób, choć Jatin's answer jest sposób chłodnicy:

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

podnoszony z:

1

To działa jak czar dla mnie:

@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; 
     } 
    } 
Powiązane problemy