spring - 将图像上传到 Spring Boot 和 S3 all In-Memory

标签 spring amazon-web-services spring-boot amazon-s3 multipart

我有一个 Angular webapp,它使用 Spring Boot REST 服务作为其支持的 web 服务。

我正在为用户添加“个人资料”功能,作为其中的一部分,我想建立一个端点,允许用户为自己上传个人资料图像并立即将这些文件上传到 S3(我将在其中托管所有图像)。

看几个Spring Boot/文件上传教程:

  • http://www.mkyong.com/spring-boot/spring-boot-file-upload-example/
  • I update avatar image and display it but the avatar does not change in Spring Boot , why?
  • 许多其他

  • 似乎处理此类文件上传的标准方法是公开接受 MultipartFiles 的 Controller 端点。像这样:
    @RestController
    @RequestMapping("/v1/profiles")
    public class ProfileController {
        @PostMapping("/photo")
        public ResponseEntity uploadProfilePhoto(@RequestParam("mpf") MultipartFile mpf)
            // ...
    }
    

    查看所有这些代码,我不知道 MultipartFile实例在内存中,或者如果 Spring 将其位置设置在磁盘上的某个位置(可能在 /tmp 下?)。

    看着AWS S3 Java SDK tutorial ,这似乎是上传 的标准方式基于磁盘的文件 是这样的:
    File file = new File(uploadFileName);
    s3client.putObject(new PutObjectRequest(bucketName, keyName, file));
    

    所以看起来我必须在磁盘上有一个文件才能上传到 S3。

    我想知道是否有办法将所有内容保存在内存中,或者这是否是一个坏主意,我应该坚持使用磁盘/File实例!
  • 有没有办法将整个配置文件图像( MultipartFile )保存在 Controller 方法中的内存中?
  • 有没有办法提供(也许通过序列化?!)MultipartFile S3 的实例 PutObjectRequest ?
  • 或者这都是一个糟糕的主意(如果是这样,为什么?!)?
  • 最佳答案

    Is there a way to keep the entire profile image (MultipartFile) in-mempory inside the controller method?



    不,没有办法将图像文件保存在内存中,因为 java 中的 File 对象代表文件系统中的路径。

    Is there a way to feed (maybe via serialization?!) a MultipartFile instance to S3's PutObjectRequest?



    不,从 S3 的 API 文档中,S3 无法在上传之后/期间为您反序列化为图像文件。

    Or is this all a terrible idea (if so, why?!)?



    这取决于您的具体情况,但通常不是首选。
    如果——同时上传图片的用户不多,你的内存是可能 足以应付。
    否则 - 您很容易遇到内存不足的问题。

    如果你坚持这样做,S3 API 可以上传一个 InputStream (如果我没记错的话)。您可以将多部分文件转换为 InputStream .
    This SO thread talks about uploading to S3 with InputStream

    你也可以看看File.createTempFile()创建一个临时文件。

    关于spring - 将图像上传到 Spring Boot 和 S3 all In-Memory,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48570020/

    相关文章:

    java - AuthorizationService 中 getAuthority() 上的 SonarQube 警告

    java - 使用 @RefreshScope 刷新 Bean,无需更改配置

    python - 即使关闭本地机器,如何在 AWS EC2 上运行进程?

    java - 在 Elastic Beanstalk 上更改 Apache Tomcat 的文件编码

    amazon-web-services - 我当前的 AWS 架构能否扩展到每天 20,000 名访问者?我该如何改进它?

    spring - 找不到mainClassName,不需要

    java - 为什么我的 SecurityWebFilterChain 没有被调用?

    java - 停止 <任务 :scheduler> tasks

    spring-boot - Spring Boot 和 Spring Data Moore 发布

    java - Spring配置到底是什么意思?