简体   繁体   English

如何将图像直接上传到 S3,而不让在 Ec2 中运行的 java webapp 存储 Multipart 图像?

[英]How to upload an image directly to S3, without letting java webapp running in Ec2 to store the Multipart image?

In my laptop, localhost,在我的笔记本电脑中,本地主机,

Following code uploads image uploaded via browser, and then it uploads to S3.以下代码上传浏览器上传的图片,然后上传到S3。

I came to know that Elastic Beanstalk applications run on Amazon EC2 instances that have no persistent local storage.我开始知道 Elastic Beanstalk 应用程序在没有持久本地存储的 Amazon EC2 实例上运行。 We should write the file directly to S3.我们应该将文件直接写入 S3。

How to write file directly to S3, when my java webapp runs in Ec2 instances?当我的 java webapp 在 Ec2 实例中运行时,如何将文件直接写入 S3?

This is the code I use to upload image to S3 which works fine in my localhost这是我用来将图像上传到 S3 的代码,它在我的本地主机中运行良好

try {
            final ObjectMetadata objectMetadata = new ObjectMetadata();
            objectMetadata.setContentType(file.getContentType());
            byte[] contentBytes = null;
            try {
              final InputStream is = file.getInputStream();
              contentBytes = IOUtils.toByteArray(is);
            } catch (final IOException e) {
              log.error("Failed while reading bytes from %s" + e.getMessage());
            }

            final Long contentLength = Long.valueOf(contentBytes.length);
            objectMetadata.setContentLength(contentLength);
            objectMetadata.setHeader("filename", fileNameWithExtn);

            /*
             * Reobtain the tmp uploaded file as input stream
             */
            final InputStream inputStream = file.getInputStream();

            final File convFile = new File(fileNameWithExtn);
            file.transferTo(convFile);


            FileUtils.copyInputStreamToFile(inputStream, convFile);
            try {

              final AmazonS3 s3Client = AmazonS3ClientBuilder.standard().build();
              versionId = s3Client.putObject(new PutObjectRequest("bucketName", name, convFile))
                  .getVersionId();
            } catch (final AmazonServiceException ase) {
              System.out.println("Caught an AmazonServiceException, which"
                  + " means your request made it "
                  + "to Amazon S3, but was rejected with an error response" + " for some reason.");
              System.out.println("Error Message:    " + ase.getMessage());
              System.out.println("HTTP Status Code: " + ase.getStatusCode());
              System.out.println("AWS Error Code:   " + ase.getErrorCode());
              System.out.println("Error Type:       " + ase.getErrorType());
              System.out.println("Request ID:       " + ase.getRequestId());
            } catch (final AmazonClientException ace) {
              System.out.println("Caught an AmazonClientException, which means"
                  + " the client encountered " + "an internal error while trying to "
                  + "communicate with S3, " + "such as not being able to access the network.");
              System.out.println("Error Message: " + ace.getMessage());
            }
          } catch (final Exception e) {
            log.error("You failed to upload " + name + " => " + e.getMessage());
          }

I checked this article Converting MultipartFile to java.io.File without copying to local machine but one answers says it doesn't work for File or String , while other answers doesn't have clear cut code or answer.我查看了这篇文章Converting MultipartFile to java.io.File without copying to local machine但一个答案说它不适用于 File 或 String ,而其他答案没有明确的代码或答案。

Please help.请帮忙。

您可以尝试直接使用前端,查看有关直接将 html 表单提交到 s3 的 S3 文档 检查参考链接 将表单数据直接上传到 AWS S3 - Stuff... And Things... ( https://stuff-things.net/2016/ 03/30/uploading-form-data-directly-to-aws-s3/ ) 使用 HTML5 和 Backbone.js ( http://www.tweetegy.com/2012/01)从 Web 浏览器将图像文件直接保存到 S3 /save-an-image-file-directly-to-s3-from-a-web-browser-using-html5-and-backbone-js/ )

You can do so through java as well.你也可以通过java来做到这一点。 Below code stores the file directly to s3 without storing it locally on EC2下面的代码将文件直接存储到 s3,而不将其本地存储在 EC2 上

public boolean uploadFileDirectlyToS3(MultipartFile multipartFile, String keyName) {
        ObjectMetadata data = new ObjectMetadata();
        try {
            data.setContentType(multipartFile.getContentType());
            data.setContentLength(multipartFile.getSize());
            s3Client.putObject(CORE_BUNDLE.getString("bucket.name"), keyName, multipartFile.getInputStream(), data); 
//KeyName is the specific and unique path where you wanna place your file in s3
            return true;
        } catch (Exception e) {
            logger.error("Error occured while uploading file to s3 having name: "+multipartFile.getOriginalFilename(), e);
            return false;
        }
    }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM