我想要返回這樣的圖像。Spring MVC:如何從控制器返回圖像?
@RequestMapping(value = "admin/image/{userId}")
public ResponseEntity<byte[]> getPhoto(@PathVariable int userId) throws IOException {
UserDB userDB = UserDBService.getUserWithId(userId);
if (userDB != null) {
try {
byte[] image;
try {
String path = ApplicationPropertiesConstants.SAFESITE_DOCUMENTS_DIRECTORY + userDB.getSite().getId() + "\\342.png";
InputStream is = new FileInputStream(path);
BufferedImage img = ImageIO.read(is);
ByteArrayOutputStream bos = new ByteArrayOutputStream();
ImageIO.write(img, "png", bos);
final HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.IMAGE_PNG);
return new ResponseEntity<byte[]>(IOUtils.toByteArray(is), headers, HttpStatus.CREATED);
} catch (FileNotFoundException e) {
image = org.apache.commons.io.FileUtils.readFileToByteArray(new File("dfd"));
}
return null;
} catch (IOException ignored) {
}
}
return null;
}
儘管當我訪問url時圖片不顯示。
任何想法,爲什麼發生這種情況?我需要使用Apache Tiles嗎?目前我正在使用jstlView。
<bean id="viewResolver" class="org.springframework.web.servlet.view.UrlBasedViewResolver">
<property name="viewClass" value="org.springframework.web.servlet.view.JstlView" />
<property name="prefix" value="/WEB-INF/jsp/" />
<property name="suffix" value=".jsp" />
</bean>
你什麼反應? – zeroflagL
無法加載響應數據 – OneTwo
如果您有'InputStream',無論如何您可以返回一個'ResponseEntity',其主體是'new InputStreamResource(inputStream)'。 –
zeroflagL