【问题标题】:Spring boot - image upload failedSpring boot - 图片上传失败
【发布时间】:2018-09-19 02:14:36
【问题描述】:

我正在使用 spring 上传图像,但是当我尝试将文件保存在我的一个项目文件夹中时出现错误。

错误:

java.nio.file.NoSuchFileException: \resources\images\photo001.png
There was an unexpected error (type=Internal Server Error, status=500).
\resources\images\photo001.png

我有这条路:

 String path = "\\resources\\images\\";
 String path2 = "c:\\temp\\";

Path2 有效,但我想将我的文件保存在项目中,而不传递从 C: 开始的整个路径...

我应该通过什么通道将其保存在项目的资源/图像中? 我的项目如下所示: https://i.imgur.com/Dn6wXAK.png

【问题讨论】:

  • 您打算从您的项目或从您的项目外可能存在的任何目录加载文件?

标签: file spring-boot path upload


【解决方案1】:

试试“图片/”

src/main/resources 中的所有文件都复制到 classes/ 中,因此在您的 jar 或 war 中没有文件夹 /resources。

您也不应该使用特定于 Windows 的反斜杠“\”,而应使用 改用 /images/ 可以使您的构建具有可移植性,因此它也可以在 Linux 上运行。

【讨论】:

    【解决方案2】:

    Senio,如果您使用的是 Spring Boot,那么有一个名为 Spring Content 的项目将允许您用很少的代码行创建一个图像存储。

    您需要做的就是添加以下 Spring Content 依赖项(假设是 maven):-

    <dependencies>
        <!-- Standard Spring Boot -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <dependency>
            <groupId>javax.servlet</groupId>
            <artifactId>servlet-api</artifactId>
            <version>2.3</version>
        </dependency>
    
        <!-- Spring Content -->
        <dependency>
            <groupId>com.github.paulcwarren</groupId>
            <artifactId>spring-content-fs-boot-starter</artifactId>
            <version>0.0.10</version>
        </dependency>
        <dependency>
            <groupId>com.github.paulcwarren</groupId>
            <artifactId>spring-content-rest-boot-starter</artifactId>
            <version>0.0.10</version>
        </dependency>
    </dependencies>
    

    在您的 Spring Boot Application 类中,创建一个 ImageStore 接口。将其注释为 REST 资源。这会导致 Spring Content 注入一个实现(文件系统的此接口)以及 REST 端点,从而使您不必自己编写任何此代码:-

        @SpringBootApplication 
        public class DemoApplication {
    
            public static void main(String[] args) {        
               SpringApplication.run(DemoApplication.class, args);  
            }
    
            @StoreRestResource(path="images")   
            public interface ImageStore extends Store<String> {} 
        }
    

    默认情况下,Spring Content FS 会在 java.io.tmpdir 下创建一个 store。因此,您还需要将 SPRING_CONTENT_FS_FILESYSTEM_ROOT 环境变量设置为指向“存储”的根目录; c:\临时\资源\图像。

    启动应用程序,您将能够通过 POST(或 PUTting)将图像上传到:-

    /images/some/path/image-1.jpg

    (这也支持GET(下载)和DELETE。)

    您会在 c:\temp\resources\images\some\path\image-1.jpg 下找到上传的图片

    HTH

    【讨论】:

      猜你喜欢
      • 2014-10-25
      • 2016-04-11
      • 2014-07-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-02-08
      相关资源
      最近更新 更多