我有这个Spring端点,它返回文件:
@RequestMapping(value = "/files/{merchant_id}", method = RequestMethod.GET)
public void getFile(@PathVariable("merchant_id") Integer merchant_id, HttpServletResponse response) {
try {
File initialFile = new File("/opt/1/Why_Brookfield_Callout_3x.png");
InputStream is = FileUtils.openInputStream(initialFile);
org.apache.commons.io.IOUtils.copy(is, response.getOutputStream());
response.flushBuffer();
} catch (IOException ex) {
throw new RuntimeException("IOError writing file to output stream");
}
}
但是当我下载文件时,我得到的是文本。 如何将那里的文件类型设置为.png文件?
答案 0 :(得分:2)
在您的produces = MediaType.IMAGE_PNG
中添加@RequestMapping
有关更多媒体类型,请参见https://docs.spring.io/spring/docs/current/javadoc-api/org/springframework/http/MediaType.html
因此方法定义变为:
@RequestMapping(value = "/files/{merchant_id}", method = RequestMethod.GET, produces = org.springframework.http.MediaType.IMAGE_PNG)