存储图片路径方式保存和显示图片

HTML:

  <form  method="POST" enctype="multipart/form-data" id="imgupload2">   
    <br>请选择图片:<input id="imgfile2" name="imgfile2" size="80" type="file"><input name="upload"type="button" value="开始导入2" οnclick="checkform2();"/>  
  </form>


JS:

$('#imgupload2').ajaxSubmit({
  url:"upload/imgImport2",
  type: 'POST', 
  dataType: "json",
  success:function(result){
    console.log(result);
    //$('#img2').attr("src",result.message);
  },
  error:function(result){
    console.log(result);
  }
});


控制层:

@RequestMapping(value = "/imgImport2")
@ResponseBody
protected JsonResult uploadXmInfo2(HttpServletRequest req,HttpServletResponse res) throws Exception {
   //将文件上传到本地磁盘目录下
   String updoadFilePath = req.getServletContext().getRealPath("")+ "upload";
   System.out.println("updoadFilePath:"+updoadFilePath);
   File updoadDir = new File(updoadFilePath);
   if (!updoadDir.exists()) {
     updoadDir.mkdirs();
   }
   // 转型为MultipartHttpRequest:
   MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) req;
   // 获得文件:
   MultipartFile file = multipartRequest.getFile("imgfile2");
   //获取文件名
   String filename = file.getOriginalFilename();
   //获取文件路径
   String fullname = updoadFilePath + File.separator + filename;
   System.out.println("fullname"+fullname);
   File targetFile = new File(fullname);
   if (targetFile.exists()) {
     targetFile.delete();
   }
   targetFile.createNewFile();//
   int rtnInt = FileUtil.CopyFile(file, fullname);
   if(rtnInt!=0){
      return new JsonResult(2,"图片上传失败");
   }
   uploadService.file2db(fullname);//将全路径保存在数据库
   return new JsonResult(1,"成功");
             
}


============================保存图片完成=======================

============================显示图片==========================

自己本打算传递绝对路径到前端,让浏览器自己找到图片,但是不可以:Not allowed to load local resource: file:///C:/apache-tomcat- 8.5.6/webapps/MyLab/upload/2.png

所以采用下面的方式:

html:    

 图片2:<img src="<%=basePath%>/upload/showImage" id="img2" class='file-preview-image' width="100px" height="100px">

控制层(将图片以流的方式读出然后写入到img):

/**
* 显示图片
* @param re
* @param response
* @param pic_addr
*/
@RequestMapping(value = "/showImage")
   public void showImage(HttpServletRequest re,HttpServletResponse response,String pic_addr){//pic_addr:图片路径(d:\\upload\a.jpg)
    //response.setContentType("text/html; charset=UTF-8");
    response.setContentType("image/*");
    FileInputStream fis = null; 
    OutputStream os = null; 
    try{
        //fis = new FileInputStream(re.getSession().getServletContext().getRealPath("/res/fileUpload")+"/"+pic_addr);
        //在这里我直接用了一个已经写好的路径
        fis = new FileInputStream("C:\\apache-tomcat-8.5.6\\webapps\\MyLab\\upload\\2.png");
        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();
        }
     }
}


  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值