【发布时间】:2019-11-29 12:46:40
【问题描述】:
我正在将文件保存在我的 S3 存储桶上,但我注意到为此我使用了 FileOutPutStream,如下所示:
private UploadedFile file; // This is from PrimeFaces, the file that the client wishes to upload
File uploadedFile = new File(file.getFileName()); // Leaving the file like this creates the file on my IDE folder AFTER executing the next two lines, thats why I though the next lines were an error.
FileOutputStream fileOutput = new FileOutputStream(uploadedFile);
fileOutput.write(file.getContents());
所以这行代码负责在我的设备上写入文件,我首先认为这是一个错误或者没有必要,因为我不太了解文件上传到亚马逊,所以我删除了这两行因为我注意到我的上传方法只需要文件和文件名,如下所示:
businessDelegatorView.uploadPublicRead("mybucketname", fileName, fileToUpload);
所以我虽然这不是必需的,而且只是复制文件:
FileOutputStream fileOutput = new FileOutputStream(uploadedFile);
fileOutput.write(file.getContents());
但是我注意到,如果我删除它们,上传将不起作用,因为它会抛出 FileNotFoundException,所以我开始搜索并从 BalusC 找到 this post,我明白了我必须定义文件所在的路径来自我的客户的将被保存以供以后上传,就像在这种情况下到亚马逊 s3 存储桶一样,但我想知道,例如,在生成 .WAR 时这样做是否会起作用:
File uplodadFile = new File("C:/xampp/apache/conf", file.getFileName());
FileOutputStream fileOutput = new FileOutputStream(uploadFile);
fileOutput.write(file.getContents());
我将文件保存在那里作为测试,但我不知道或不确定FileOutPutStream 是否是正确的选择,我不知道其他方式。
这也是上面代码执行后上传的方法,没有FileOutPutStream它不会工作,因为文件不在我的设备中
AmazonS3 amazonS3 = buildAmazonS3();
try {
amazonS3.putObject(new PutObjectRequest(bucketName, key, file).withCannedAcl(CannedAccessControlList.PublicRead));
只是希望有人为我更清楚一些事情,例如在这里放置的最佳路径是什么?
File uplodadFile = new File("C:/xampp/apache/conf", file.getFileName());
或者真的没关系,我只需要记住 .WAR 将部署在哪台机器上?谢谢
【问题讨论】:
-
为什么要将 UploadedFile 的内容写入磁盘只是为了从磁盘读回并发送到 S3?只需将内容直接发送到 S3。请参阅docs.aws.amazon.com/AWSJavaSDK/latest/javadoc/com/amazonaws/…,它将 InputStream 作为参数,以及 primefaces.org/docs/api/6.1/org/primefaces/model/…,它允许从 UploadedFile 中获取 InputStream。
标签: java amazon-s3 file-upload