春季启动 - 映像上传失败



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

错误:

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

我有这条路:

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

Path2 有效,但我想将我的文件保存在项目中,而不从 C:...

我应该传递什么通道才能将其保存在项目的资源/图像中? 我的项目看起来像这样: https://i.stack.imgur.com/mKfpq.png

试试 'images/'

src/main/resources 中的所有文件都被复制到类中/所以在你的 jar 或 war 中没有文件夹/resources。

您也不应该使用特定于窗口的反斜杠"\",而应使用 使用/images/代替,这会让你的构建可移植,这样它也可以在 Linux 上运行。

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 下创建一个存储。 因此,您还需要将SPRING_CONTENT_FS_FILESYSTEM_ROOT环境变量设置为指向"存储"的根目录;c:\temp\resources\images.

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

/

images/some/path/image-1.jpg

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

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

呵呵

最新更新