【问题标题】:How to a list of images from mysql using spring and hibernate如何使用spring和hibernate从mysql中获取图像列表
【发布时间】:2017-03-16 09:59:16
【问题描述】:

我以字节格式将图像存储在 mysql 数据库表中。当我从数据库中检索该图像时,我得到了这样的结果。

所以dispatcher-servlet.xml如下

<beans:bean id="multipartResolver"
        class="org.springframework.web.multipart.commons.CommonsMultipartResolver">

         <!-- setting maximum upload size -->
        <beans:property name="maxUploadSize" value="100000" />

    </beans:bean>

pom.xml

<!-- Apache Commons FileUpload --> 
<dependency>
    <groupId>commons-fileupload</groupId>
    <artifactId>commons-fileupload</artifactId>
    <version>1.3.1</version>
</dependency>

<!-- Apache Commons IO --> 
<dependency>
    <groupId>commons-io</groupId>
    <artifactId>commons-io</artifactId>
    <version>2.4</version>
</dependency>

driversList.jsp

<div style="color: teal; font-size: 20px">List Of Drivers</div>
            <c:if test="${!empty listDrivers}">
                <table border="1" bgcolor="black" width="600px">
                    <tr
                        style="background-color: teal; color: white; text-align: center;"
                        height="40px">
                        <th width="60">Name</th>
                        <th width="80">License Number</th>
                        <!--  <th width="80">Password</th> -->
                        <th width="80">Phone</th>

                        <th width="80">Password</th>
                        <th width="80">Address</th>
                        <th width="80">Photo</th>

                    </tr>
                    <c:forEach items="${listDrivers}" var="driver">
                        <tr
                            style="background-color: white; color: black; text-align: center;"
                            height="30px">

                            <td>${driver.name}</td>
                            <td>${driver.license}</td>
                            <td>${driver.number}</td>

                            <td>${driver.password}</td>
                            <td>${driver.address}</td>
                            <td><img src="/momcab1/myImage/imageDisplay?id=${driver.id}"/></td>

                        </tr>
                    </c:forEach>
                </table>
            </c:if>
            <!-- Content data end -->
            <br> <br> <br> <br> <br> <br> <br>
            <br> <br> <br>
        </div>

DriverController.java

@RequestMapping(value = "/DriversList", method = RequestMethod.GET)
    public String listUsers(Model model,HttpServletRequest req,HttpServletResponse res) {

        HttpSession session =req.getSession();
         if(session.getAttribute("emailId")==null)
         {
             return "redirect:/login";
         }
         System.out.println("MY NAME IS GO PINK");
        model.addAttribute("listDrivers", this.driverService.listDrivers());
        return "driversList";
    }

ImageController.java

@Controller
@RequestMapping("/myImage")
public class ImageController {

    @Value("${login_session_token_timeout_mnts}")
    private String loginSessionTokenTimeoutMnts;

    private DriverService driverService;

    @Autowired(required = true)
    @Qualifier(value = "driverService")
    public void setDriverService(DriverService ds) {
        this.driverService = ds;
    }

    @RequestMapping(value = "/imageDisplay", method = RequestMethod.GET)
      public void showImage(@RequestParam("id") Integer id, HttpServletResponse response,HttpServletRequest request) 
              throws ServletException, IOException{


        Driver item = driverService.getDriverById(id);       
        response.setContentType("image/jpeg, image/jpg, image/png, image/gif");
        response.getOutputStream().write(item.getBlobImg());


        response.getOutputStream().close();
    }

}

驱动程序.java

@Column(name = "photo")
    private byte[] blobImg;

所以在这里,当一个人点击“驱动程序列表”时,请求映射会转到DriverController.java"/DriversList" 但在我的driversList.jsp 中,有一个图像要从mysql 数据库表中显示。但是当页面加载时,它甚至不会进入"&lt;img src&gt;" 中给出的控制器请求映射 它显示一个“十字标记”,如下所示。对此的任何帮助将不胜感激。

谢谢你

我尝试了enter link description here中给出的代码

【问题讨论】:

    标签: java mysql spring hibernate multipartform-data


    【解决方案1】:

    Spring MVC: How to return image in @ResponseBody? 之前已经回答了这个问题。您可能缺少编码或类似的东西是最有可能的候选人。但有什么关系,只要使用其他人都在使用的、人人都知道的方法就行了。

    举个例子

    public class HELLOWORLD {
    
    
      class FooEntity {
    
        // TODO - ids and other stuff
    
        @Lob @Basic(fetch = FetchType.LAZY)
        private byte[] imageBytes;
    
        public byte[] getImageBytes() {
          return imageBytes;
        }
      }
    
      interface FooService {
        public FooEntity get(int id);
      }
    
    
      public static byte[] bufferedImageToByteArray(BufferedImage img) throws IOException
      {
          ByteArrayOutputStream baos = new ByteArrayOutputStream();
          ImageIO.write(img, "png", baos ); // I think this doesn't matter, I have jpg here
          return baos.toByteArray();
      }
    
      FooService fooService;
    
      @RequestMapping(value = "/foo/image/{id}")
      @ResponseBody
      public byte[] GetUserImageTiny(Model model, @PathVariable Integer id) throws IOException
      {   
          FooEntity fooEntity = fooService.get(id);
          byte[] imageInByte = fooEntity.getImageBytes();
          // you may be able to just go:
          // return imageInByte;
          // but I actually create the image:
          InputStream in = new ByteArrayInputStream(imageInByte);
          BufferedImage bImageFromConvert = ImageIO.read(in); // you could then debug here, write the image to a file to test if it's all good.
          // I sometimes resize the image too which I would do here
          // otherwise just return the image
          return bufferedImageToByteArray(bImageFromConvert);
      }
    
    }
    

    【讨论】:

      【解决方案2】:

      我得到了答案…………

      是我在数据库中添加图片错误,所以我修改了添加图片到数据库的代码

      @RequestMapping(value = "/Drivers/add", method = RequestMethod.POST)
          public String addUser(@ModelAttribute("driver") Driver driver,BindingResult result,@RequestParam("blobImg") MultipartFile blobImg) {
      
              if (driver.getId() == 0) {
                  // new user, add to DB
      
                  System.out.println("Name:" + driver.getName());
      
                  System.out.println("File:" + blobImg.getSize());
                  System.out.println("ContentType:" + blobImg.getContentType());
      
                          try {
                              driver.setBlobImg(blobImg.getBytes());
                          } catch (IOException e) {
                              // TODO Auto-generated catch block
                              e.printStackTrace();
                          }
      
                       }
      
      
                      this.driverService.addDriver(driver);
      
      
      
      
      
              return "redirect:/Drivers";
      
          }
      

      然后我通过这段代码获取

      @RequestMapping(value = "/imageDisplay/{id}", method = RequestMethod.GET)
            public String showImage(@PathVariable("id") int id, HttpServletResponse response,HttpServletRequest request) 
                    throws ServletException, IOException{
      System.out.println("Image isn't coming");
      System.out.println("Id is"+id);
              Driver item = driverService.getDriverById(id);    
                       try {
              response.setContentType("image/jpeg, image/jpg, image/png, image/gif");
              response.getOutputStream().write(item.getBlobImg());
      
      
              response.getOutputStream().close();
                       }
                       catch(Exception e) {
                           e.printStackTrace();
                       }
             return "driversList";
          }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2020-08-05
        • 2015-01-28
        • 1970-01-01
        • 2021-09-10
        • 2012-05-27
        • 2019-04-05
        • 2015-01-04
        • 1970-01-01
        相关资源
        最近更新 更多