1. 程式人生 > >模擬從圖片伺服器載入圖片

模擬從圖片伺服器載入圖片

整個流程就是,先把圖片名從資料庫獲取出來,然後傳到前臺頁面,通過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();
        }
    }
}