我有一个返回文件的 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 文件?
最佳答案
在您的@RequestMapping
中添加products = MediaType.IMAGE_PNG
参见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)
关于java - 下载时如何设置文件类型?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57547682/