SpringBoot 项目 读取本地图片显示页面的方法
前台:
//picPath 位图片在服务器上存的位置,如“D:/gsPic/20220105/20220105192943227.jpg” //name为项目访问名称,没有可不写 <img src="/name/getPic?picName=+ picPath">
后台:
1.在SpringBootApplication启动类中添加如下方法,配饰访问路径
/** * 在SpringBootApplication启动类中添加如下方法 * @return */ @Bean public ServletRegistrationBean getServletRegistrationBean() { //放入自己的Servlet对象实例 ServletRegistrationBean bean = new ServletRegistrationBean(new GetPic()); //访问路径值 bean.addUrlMappings("/getPic"); //一定要返回ServletRegistrationBean return bean; }
2.新建类,去把图片以流的形式写回页面
public class GetPic extends javax.servlet.http.HttpServlet implements javax.servlet.Servlet { /** * */ private static final long serialVersionUID = 1L; /* * (non-Java-doc) * * @see javax.servlet.http.HttpServlet#doGet(HttpServletRequest request, * HttpServletResponse response) */ protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doPost(request, response); } /* * (non-Java-doc) * * @see javax.servlet.http.HttpServlet#doPost(HttpServletRequest request, * HttpServletResponse response) */ protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String picName=request.getParameter("picName").toString(); File f = null; f = new File(picName); if (f.exists()) { tofile(f, response, "image/jpg"); } } public void tofile(File file, HttpServletResponse response, String contentType){ try { FileInputStream in = new FileInputStream(file); byte[] buf = new byte[(int) in.available()]; in.read(buf); response.setContentType(contentType); OutputStream toClient = response.getOutputStream(); toClient.write(buf); toClient.flush(); toClient.close(); in.close(); } catch (Exception e) { //e.printStackTrace(); } } }
上一篇:
IDEA上Java项目控制台中文乱码