有没有办法使用弹簧控制器映射图像文件?在我的spring应用程序中,我希望将图像存储在目录src / main / resources中(我使用maven)并使用如下方法访问它们:
@RequestMapping(value="image/{theString}")
public ModelAndView image(@PathVariable String theString) {
return new ModelAndView('what should be placed here?');
}
字符串theString
它是图像名称(没有扩展名)。通过这种方法,我应该能够以这种方式访问我的图像:
/webapp/controller_mapping/image/image_name
任何人都可以指明这样做的方向吗?
答案 0 :(得分:0)
您可以返回HttpEntity<byte[]>
。 Construct新实例提供图像字节数组和必要的标题,如内容长度和mime类型,然后从您的方法返回它。可以使用类加载器getResourceAsStream
method获取图像字节。
答案 1 :(得分:0)
这对我有用。它可以使用一些清理,但它的工作原理。 ServiceException只是一个简单的基本异常。
祝你好运!
package com.dhargis.example;
import java.io.File;
import java.io.IOException;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.io.FileUtils;
import org.apache.log4j.Logger;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
@Controller
@RequestMapping("/image")
public class ImageController {
private static final Logger log = Logger.getLogger(ImageController.class);
private String filestore = "C:\\Users\\dhargis";
//produces = "application/octet-stream"
@RequestMapping(value = "/{filename:.+}", method = RequestMethod.GET)
public void get( @PathVariable String filename,
HttpServletRequest request,
HttpServletResponse response) {
log.info("Getting file " + filename);
try {
byte[] content = null;
File store = new File(filestore);
if( store.exists() ){
File file = new File(store.getPath()+File.separator+filename);
if( file.exists() ){
content = FileUtils.readFileToByteArray(file);
} else {
throw new ServiceException("File does not exist");
}
} else {
throw new ServiceException("Report store is required");
}
ServletOutputStream out = response.getOutputStream();
out.write(content);
out.flush();
out.close();
} catch (ServiceException e) {
log.error("Error on get", e);
} catch (IOException e) {
log.error("Error on get", e);
}
}
}
<!-- begin snippet: js hide: false -->