Spring并从Web服务器外部提供文件

时间:2012-03-19 20:39:28

标签: spring spring-mvc

我希望spring从/tmp...目录提供某些文件,特定目录直到服务器启动后不久才确定,因此使用<mvc:resources location="/images/**" mapping="/absolute/path/to/image/dir"/>似乎无法正常工作。

2 个答案:

答案 0 :(得分:1)

正如Dave Newton所说 - 从控制器流出来。一个非常基本的实现:

@RequestMapping("/static/temp/{path}")
public void getResource(@PathVariable path, OutputStream os) {
     //TODO proper IO management
     InputStream is = new BufferedInputStream(new FileInputStream("/temp/" + path));
     IOUtils.copy(is, os);
}

答案 1 :(得分:0)

我这样做:

@RequestMapping(value="/staticFile/{id}", method = RequestMethod.GET)
public void getPhotoRide2(HttpServletResponse response, @PathVariable int id) {
            try {
                FileInputStream in = new FileInputStream("your file");
                OutputStream out = response.getOutputStream();
                response.setContentType("your mime type");
                byte[] buf = new byte[1024];
                int count = 0;
                while ((count = in.read(buf)) >= 0) {
                    out.write(buf, 0, count);
                }
               in.close();
               out.flush();
               out.close();
           } catch (Exception e) {}

}