gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 06:26:52 24 4
gpt4 key购买 nike

在我的笔记本电脑中,本地主机,

以下代码上传通过浏览器上传的图片,然后上传到S3。

我了解到 Elastic Beanstalk 应用程序在没有持久本地存储的 Amazon EC2 实例上运行。我们应该将文件直接写入S3。

当我的 java web 应用程序在 Ec2 实例中运行时,如何将文件直接写入 S3?

这是我用来将图像上传到 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());
}

我查了这篇文章Converting MultipartFile to java.io.File without copying to local machine但一个答案说它不适用于 File 或 String ,而其他答案没有明确的代码或答案。

请帮忙。

最佳答案

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

关于java - 如何将图像直接上传到S3,而不让在Ec2中运行的java webapp来存储多部分图像?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47007829/

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