如何使用spring mvc将图像上传到webapp / resources / images目录? [英] How to upload an image to webapp/resources/images directory using spring mvc?

查看:1052
本文介绍了如何使用spring mvc将图像上传到webapp / resources / images目录?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有存储库类,我想在将产品详细信息添加到存储库之前将来自MultipartFile的图像存储到webapp / resources / images目录?

I have repository class where I want to store the image that is coming from MultipartFile to webapp/resources/images directory before adding the product details to the repository ?

@Override
public void addProduct(Product product) {
    Resource resource = resourceLoader.getResource("file:webapp/resources/images");

     MultipartFile proudctImage = product.getProudctImage();

     try {
        proudctImage.transferTo(new File(resource.getFile()+proudctImage.getOriginalFilename()));
    } catch (IOException e) {
        throw new RuntimeException(e);
    }
    listOfProducts.add(product);
}

我的存储库类是ResourceLoaderAware。我收到fileNotFoundException,imagesDesert.jpg是我试图上传的图片

my repository class is ResourceLoaderAware. I am getting fileNotFoundException, "imagesDesert.jpg" is the image I am trying to upload

java.io.FileNotFoundException: webapp\resources\imagesDesert.jpg (The system cannot find the path specified)


推荐答案

最后我能够解决这个问题,我们不需要指定文件:前缀,而且默认情况下 resourceLoader.getResource()将在我们的Web应用程序的根目录中查找资源,因此无需指定 webapp 文件夹名称。所以最后以下代码适用于我

Finally I could able to fix this problem, we need not specify the file: prefix, and moreover by default resourceLoader.getResource() will look for resources in the root directory of our web application, So no need of specifying the webapp folder name. So finally the following code works for me

@Override
public void addProduct(Product product) {

    MultipartFile proudctImage = product.getProudctImage();

    if (!proudctImage.isEmpty()) {
        try {
            proudctImage.transferTo(resourceLoader.getResource("resources/images/"+product.getProductId()+".png").getFile());

        } catch (Exception e) {
            throw new RuntimeException("Product Image saving failed", e);
        }
    }

    listOfProducts.add(product);
}

这篇关于如何使用spring mvc将图像上传到webapp / resources / images目录?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆