使用Spring MVC从本地路径中删除图像

时间:2017-03-08 12:12:53

标签: java spring hibernate jsp spring-mvc

以下是使用Spring MVC将Image保存到本地系统的方法

private void saveProductImage(Product product)
    {
        System.out.println("Product Image - "+ product.getProduct_image());
            try{
                if(product.getProduct_image()!= null)
                {
                    Path path=Paths.get("E://Eclipse//WorkSpace//TechGrab//src//main//webapp//resources//images//product-images//"+ product.getProduct_id()+".png");
                    product.getProduct_image().transferTo(new File(path.toString()));
                    System.out.println("Product Image Saved !!!");
                }
            }
            catch(Exception e)
            {
                System.out.println("Failed to Save image !!");
            }
    }

此处产品是我的模型,路径路径的对象,其中我将图像保存为产品ID od图像使用

product.getProduct_image().transferTo(new File(path.toString()));

现在 - 我想删除产品详细信息以及产品图片,所以这是我的产品详细信息被删除

@Transactional
    public void deleteProduct(String product_id) {
        Session ses = sf.openSession();
        Transaction tr = ses.beginTransaction();
        Product temp = ses.get(Product.class, product_id);
        ses.delete(temp);
        tr.commit();
        ses.close();

    }

获取产品ID的删除方法但现在仍然将图像保存在具有产品ID的本地系统中,如何删除产品图像!帮帮我吧:)

我试过这个 - 但它没有用!

private void deleteProductImage(Product product)
    {
        System.out.println("Product Image - "+ product.getProduct_image());
            try{
                if(product.getProduct_image()!= null)
                {
                    Path path=Paths.get("E://Eclipse//WorkSpace//TechGrab//src//main//webapp//resources//images//product-images//"+ product.getProduct_id()+".png");
                    Files.delete(path);
                    System.out.println("Product Image Deleted !!!");
                }
            }
            catch(Exception e)
            {
                System.out.println("Failed to Delete image !!");
            }
    }

抱歉英语不好

1 个答案:

答案 0 :(得分:2)

哦,终于得到了简单的解决方案! 我的坏,忘记了事情xD

认为答案是

@Transactional
    private void deleteProductImage(Product product)
    {
         try { 
             File file = new File("E://Eclipse//WorkSpace//TechGrab//src//main//webapp//resources//images//product-images//"+ product.getProduct_id()+".png");
             if(file.delete()) { 
                System.out.println(file.getName() + " is deleted!");
             } else {
                System.out.println("Delete operation is failed.");
                }
          }
            catch(Exception e)
            {
                System.out.println("Failed to Delete image !!");
            }
    }
Ty!关闭后