写了个Spring rest 风格的 图片加载。
package cn.tang.demo.controller.image;import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;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;
import org.springframework.web.bind.annotation.RequestParam;@Controller
@RequestMapping(value = "/image/")
public class ImageCacheController {// for restful http://localhost:8888/rest/image/load?imageName=a.jpg@RequestMapping(value = "/load", method = RequestMethod.GET)public void imageLoad(@RequestParam(value = "imageName", required = true) String imageName, HttpServletRequest request, HttpServletResponse response)throws IOException {File f = new File("c://"+imageName);if (!f.exists()) {return;}FileInputStream fis = new FileInputStream(f);byte[] buffer = new byte[1024];int len =0;try {response.setHeader("Content-Type", "image/jpg;charset=UTF-8");ServletOutputStream outputStream = response.getOutputStream();while ((len=fis.read(buffer)) > 0) {outputStream.write(buffer, 0, len);}outputStream.flush();} finally {fis.close();}}// for restful http://localhost:8888/rest/image/a.jpg@RequestMapping(value = "/{name:\\S*\\.?\\S+}", method = RequestMethod.GET)public void helloMan(@PathVariable String imageName, HttpServletRequest request, HttpServletResponse response)throws IOException {File f = new File("c://"+imageName);if (!f.exists()) {return;}FileInputStream fis = new FileInputStream(f);byte[] buffer = new byte[1024];int len =0;try {response.setHeader("Content-Type", "image/jpg;charset=UTF-8");ServletOutputStream outputStream = response.getOutputStream();while ((len=fis.read(buffer)) > 0) {outputStream.write(buffer, 0, len);}outputStream.flush();} finally {fis.close();}}}
这个是最基本的图片获取方式,我们可以把图片放入缓存中,然后通过读缓存而不是读文件来获取图片。