在 Spring 中从 Controller 返回一个文件
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/13119759/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Return a file from Controller in Spring
提问by Jatin
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?
我是春天的新手。我有一个控制器,带有几个 GET 参数的 RequestMapping。他们返回一个 String 。但是一种方法需要返回“/res/”文件夹中的文件。我怎么做?
@RequestMapping(method = RequestMethod.GET,value = "/getfile")
public @ResponseBody
String getReviewedFile(@RequestParam("fileName") String fileName)
{
return //the File Content or better the file itself
}
Thanks
谢谢
回答by Jatin
Thanks to @JAR.JAR.beans. Here is the link: Downloading a file from spring controllers
感谢@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));
}
回答by shazinltc
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
}
}
回答by Allenaz
Another way, though Jatin's answeris way cooler :
另一种方式,虽然Jatin 的回答更酷:
//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);
}
}
Lifted from:
摘自:
回答by Andrii Dobrianskiy
This works like a charm for me:
这对我来说就像一个魅力:
@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;
}
}
回答by Vikash Kumar
If you are working on local Windows machine this could be useful for you:
如果您在本地 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);
}
for testing your code you can use Postman"Use Send And Downloadnot just send"
为了测试您的代码,您可以使用邮递员“使用发送和下载而不仅仅是发送”
Another Approachto return byte:
返回字节的另一种方法:
@GetMapping("/getAppImg")
@ResponseBody
public byte[] getImage() throws IOException {
File serveFile = new File("image_path\img.jpg");
return Files.readAllBytes(serveFile.toPath());
}

