由于图片是保存在本地,浏览器不能直接访问本地的资源,所以需要一个 类 去把本地的资源读到服务器中 浏览器才可以访问服务器中读出的本地图片。
前台代码:
//C:\files_system\123.png 是本地图片路径
//${ctx}/getpicture/toFindImg?imgUrl= 是请求后台的地址
<img src='${ctx}/getpicture/toFindImg?imgUrl=C:\files_system\123.png';>
后台代码:
@RestController
@RequestMapping("getpicture")
public class GetPicture {
/**
* @param imgUrl 图片在本地磁盘的位置 如:E:/teacherCompetition/1/images/1.jpg
* @param request
* @param response
*/
@RequestMapping("/toFindImg")
public void picToJSP(@RequestParam("imgUrl") String imgUrl, HttpServletRequest request, HttpServletResponse response){
FileInputStream in;
response.setContentType("application/octet-stream;charset=UTF-8");
try {
//图片读取路径
in=new FileInputStream(imgUrl);
int i=in.available();
byte[]data=new byte[i];
in.read(data);
in.close();
//写图片
OutputStream outputStream=new BufferedOutputStream(response.getOutputStream());
outputStream.write(data);
outputStream.flush();
outputStream.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}