在Spring中从Controller返回一个文件

时间:2012-10-29 10:25:34

标签: 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
}

由于

5 个答案:

答案 0 :(得分:13)

感谢@ 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)); 
}

答案 1 :(得分: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
    }
}

答案 2 :(得分:2)

另一种方式,虽然Jatin's answer更酷:

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

取消:

答案 3 :(得分: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;
        }
    }

答案 4 :(得分:0)

如果您在本地Windows计算机上工作,这可能对您有用:

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

要测试代码,您可以使用邮递员“不仅使用发送使用发送并下载

另一种方法以返回字节

@GetMapping("/getAppImg")
    @ResponseBody
    public byte[] getImage() throws IOException {

        File serveFile = new File("image_path\\img.jpg");

        return Files.readAllBytes(serveFile.toPath());
    }