【问题标题】:Upload image in spring mvc在spring mvc中上传图片
【发布时间】:2014-12-04 06:02:01
【问题描述】:

我正在使用 spring 4 和 hibernate 4 向数据库上传和检索图像。 我已将多部分图像转换为字节数组并存储在数据库中。 我的查询是如何从数据库中检索该图像并在 jsp 中显示字节数组而不将其存储在本地系统中。

【问题讨论】:

标签: java hibernate jsp spring-mvc model-view-controller


【解决方案1】:

由于您没有提到用于存储图像的数据库结构,我假设您将其存储在 blob 数据类型中。

第 1 部分ControllerClass

从数据库中检索图像后,您必须使用Base64.encode 对该图像进行编码并将该图像映射到您的jsp(使用java.util.map)。

Map<String, Object> model = new HashMap<String, Object>();
model.put("myImage", Base64.encode(MyImage)); //MyImage (datatype 'byte[]') is the image retrieved from DB
return new ModelAndView("display", model); //display is the name of jsp on which you want to display image

第 2 部分JSP

然后通过解码字节数组在JSP上显示,

<img id="myImg" name="myImg" src="data:image/jpg;base64,<c:out value='${myImage}'/>" >

【讨论】:

    【解决方案2】:

    您可以毫无问题地做到这一点。您必须设置一个控制器,以便在浏览器请求时发送图像。但是这里,控制器并没有把它放在一个Model中给一个视图,而是直接生成HTTP响应。然后在您的 JSP 中,您只需指明相关的 URL。

    这是一个可能的(部分)示例:

    @RequestMapping(value = "/img/{imgid}")
    public void getFile(HttpServletRequest request, @PathVariable(value = "imgid") long imgid, HttpServletResponse response) throws IOException {
        contentType = "img/png"; //or what you need
        response.setContentType(contentType);
        // find the image bytes into into byte[] imgBytes
        response.setContentLength((int) imgBytes.length);
        response.setStatus(HttpServletResponse.SC_OK);
        OutputStream os = response.getOutputStream();
        os.write(imgBytes);
    }
    

    【讨论】:

      【解决方案3】:

      实际上我们正在做的是

      在dao方法中

      public InputStream get_user_photo_by_id(int id_user) throws Exception {     
          Blob blob_photo;
          String sql = "Select b_photo_file from user_master where id_user = ?";                      
      blob_photo = getJdbcTemplate().queryForObject(sql, new Object[] {id_user}, Blob.class);     
          if(blob_photo!=null)
              return blob_photo.getBinaryStream();
          else
              return null;
      }
      

      在服务方法中只是将输入流返回给控制器

      在控制器中

      @ResponseBody
      @RequestMapping(value = "admin/user/{id}/photo", method = RequestMethod.GET, produces = MediaType.IMAGE_JPEG_VALUE)
      public byte[] testphoto(@PathVariable("id") int id_sys_user, HttpSession ses) throws Exception {        
          byte[] thumb = null;
          InputStream in = UserOps.getUserPhotobyId(id_sys_user);     
          if(in!=null){
              thumb = IOUtils.toByteArray(in); 
          }
          return thumb;       
      }
      

      现在只需插入 admin/user/{id}/photo 或您希望在 中使用的任何字符串 只要它们匹配并且你得到了你的照片

      【讨论】:

        猜你喜欢
        • 2017-01-01
        • 2012-12-02
        • 1970-01-01
        • 2021-08-27
        • 2020-09-26
        • 2016-04-20
        • 1970-01-01
        • 2022-12-17
        • 2018-05-02
        相关资源
        最近更新 更多