繁体   English   中英

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

[英]Delete Image from Local path using Spring MVC

这是使用Spring MVC将图像保存到本地系统的方法

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 !!");
            }
    }

这里的产品是我的模型,和路径路径的对象,其中IM保存图像作为产品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一起保存在本地系统中,我该如何删除产品图像! ty():)

我已经尝试过了-但它不起作用!

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 !!");
            }
    }

对不起,英语不好

哦,终于有了解决方案! 我的坏,忘了事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 !!");
            }
    }

发布关闭

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM