gpt4 book ai didi

java - 保存图像的正确位置(spring/jelastic)

转载 作者:行者123 更新时间:2023-11-30 06:02:41 25 4
gpt4 key购买 nike

我打算实现用户配置文件功能,起初我找到了一个上传照片的示例,并将其保存到应用程序文件夹,如 home\jelastic\app\my_folder但有两个问题:

1) 如果我需要更新应用程序并上传新版本,我想保存这些图像,但我丢失了这些数据

2) 我无法读取照片(由于某种原因输入流为空)

public @ResponseBody byte[] getImageWithMediaType() throws IOException {
InputStream in = getClass()
.getResourceAsStream(storageService.getPath() + "/1544717586066.jpeg");
return ByteStreams.toByteArray(in);
}

那么,在 jelastic 上保存/读取照片的正确方法是什么?

最佳答案

你为什么不看看Spring Content .这旨在完全按照您的意愿行事。

假设您使用 Spring Data 来存储每个用户配置文件,您可以按如下方式将其添加到您的项目中:

pom.xml

   <!-- Java API -->
<dependency>
<groupId>com.github.paulcwarren</groupId>
<artifactId>spring-content-fs-boot-starter</artifactId>
<version>0.4.0</version>
</dependency>

<!-- REST API -->
<dependency>
<groupId>com.github.paulcwarren</groupId>
<artifactId>spring-content-rest-boot-starter</artifactId>
<version>0.4.0</version>
</dependency>

FilesystemConfiguration.java

@Configuration
public class FilesystemConfiguration {

@Bean
File filesystemRoot() {
try {
return new File("/path/to/your/user/profile/image/store");
} catch (IOException ioe) {}
return null;
}

@Bean
FileSystemResourceLoader fileSystemResourceLoader() {
return new FileSystemResourceLoader(filesystemRoot().getAbsolutePath());
}
}

User.java

@Entity
public class User {
@Id
@GeneratedValue
private long id;

...other existing fields...

@ContentId
private String contentId;

@ContentLength
private long contentLength = 0L;

@MimeType
private String mimeType = "text/plain";

...
}

UserContentStore.java

@StoreRestResource(path="userProfileImages")
public interface UserContentStore extends ContentStore<User, String> {
}

这就是您获取 REST 端点所需要做的全部工作,这些端点将允许您存储和检索与每个用户关联的内容。这实际上是如何工作的非常像 Spring Data。当您的应用程序启动时,Spring Content 将看到 spring-content-fs-boot-starter 依赖项,并知道您要将内容存储在文件系统上。它还将注入(inject) UserContentStore 接口(interface)的基于文件系统的实现。它还将看到 spring-content-rest-boot-starter 并将注入(inject)与内容存储接口(interface)对话的 REST 端点。这意味着您不必自己编写任何代码。

所以,例如:

curl -X POST/userProfileImages/{userId} -F "file=@/path/to/image.jpg"

将图像存储在文件系统上并将其与 ID 为 userId 的用户实体相关联。

curl/userProfileImages/{userId}

将再次获取它等等......实际上也支持完整的 CRUD 和视频流。

您还可以决定将内容存储在其他地方,例如数据库中(如有人评论的那样),或者通过将 spring-content-fs-boot-starter 依赖项交换为适当的 Spring Content 而将其存储在 S3 中存储模块。每种存储类型的示例是 here .

关于java - 保存图像的正确位置(spring/jelastic),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53916605/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com