码上敲享录 > java入门知识分享 > 前端图片通过src读取服务器图片

前端图片通过src读取服务器图片

上一章章节目录下一章 2020-07-14已有3383人阅读 评论(0)

html代码

<img src="imgsrc/loadimg?id=1" />

后台代码,有两种情况

第一种:图片存在数据库(使用情况,系统的一些小图片)
第二种情况:用户上传的图片(一般情况文件较大,存放在服务器)


第一种情况代码(图片存放数据库):

   @GetMapping("/loadimg")

   public ResponseEntity<byte[]> loadimg(String id) {

       //读取图片,数据库存储图片的类型为Image,接收类型为byte[]

       WxPageEdit pageEdit = pageEditServices.loadPageIcon(id);

       byte[] bytes=null;

       if(pageEdit!=null){

           bytes=pageEdit.getPageIcon();

       }

       HttpHeaders headers = new HttpHeaders();

       try {

           headers.setContentType(MediaType.IMAGE_PNG);

           headers.setContentDispositionFormData("attachment", new String("图标".getBytes("GBK"),"ISO8859-1"));

       } catch (Exception e) {

           e.printStackTrace();

       }

       return new ResponseEntity<byte[]>(bytes,headers, HttpStatus.OK);

   }


第二种情况代码(图片存放服务器)

@GetMapping("/loadimg")

   public void getImg2( HttpServletResponse response,String id ) {

       //这里省略掉通过id去读取图片的步骤。

       File file = new File("imgPath");//imgPath为服务器图片地址

       if(file.exists() && file.isFile()){

           FileInputStream fis = null;

           OutputStream os = null;

           try {

               fis = new FileInputStream(file);

               os = response.getOutputStream();

               int count = 0;

               byte[] buffer = new byte[1024 * 8];

               while ((count = fis.read(buffer)) != -1) {

                   os.write(buffer, 0, count);

                   os.flush();

               }

           } catch (Exception e) {

               e.printStackTrace();

           } finally {

               try {

                   fis.close();

                   os.close();

               } catch (IOException e) {

                   e.printStackTrace();

               }

           }

       }

   }



向大家推荐《Activiti工作流实战教程》:https://xiaozhuanlan.com/activiti
0

有建议,请留言!

  • *您的姓名:

  • *所在城市:

  • *您的联系电话:

    *您的QQ:

  • 咨询问题:

  • 提 交