模拟从图片服务器加载图片

整个流程就是,先把图片名从数据库获取出来,然后传到前台页面,通过img方式或者其他方式往后台controller发送请求,然后controller从图片服务器获取图片写入到前台页面

html

<img style="width: 150px;height: 150px;" src="${pageContext.request.contextPath}/witkeyUserComplete/showBusinessLicenseImg?imgName=${userComplete.data.businessLicense}"/>

controller

//显示营业执照  @RequestMapping("/showBusinessLicenseImg/{imgName:.+}")
@RequestMapping("/showBusinessLicenseImg")
public void showBusinessLicenseImg( String imgName, HttpSession session, HttpServletResponse response){
   //String realPath = session.getServletContext().getRealPath("/uploads/license");
    String realPath = "F:\\pic\\BusinessLicenseImg";   //这个路径换成图片服务器存放地址
    uploadPicture(imgName, response, realPath);

}
//加载图片抽取方法     使用流的方式读取写入到前台展示出来
private void uploadPicture(String imgName, HttpServletResponse response, String realPath) {
    File file = new File(realPath+File.separator+imgName);
    if(file.exists()){
        try(
                FileInputStream fileInputStream = new FileInputStream(file);
                ServletOutputStream outputStream = response.getOutputStream();
        ){
            byte[] bytes = new byte[1024];
            int count = 0;
            while((count=fileInputStream.read(bytes))!=-1){
                outputStream.write(bytes,0,count);
                outputStream.flush();
            }
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

猜你喜欢

转载自blog.csdn.net/kxj19980524/article/details/84833228
今日推荐