我是AWS的新手,现在我正在尝试编写一个独立的Java应用程序以将PDF上载到AWS S3。但是,错误:返回400。
有人可以给我一些有关如何解决此错误的一般指导吗?
public class App {
private static String PDF_PATH = "/tmp/pdf-test.pdf";
public static void main(String[] args) throws IOException {
// prepare AWS credential
BasicAWSCredentials awsCreds = new BasicAWSCredentials("xxx",
"yyy");
AmazonS3 s3Client = AmazonS3ClientBuilder.standard().withRegion("aaa")
.withCredentials(new AWSStaticCredentialsProvider(awsCreds)).build();
// upload a test PDF
byte[] pdfDoc = Files.readAllBytes((new File(PDF_PATH)).toPath());
PutObjectRequest request = new PutObjectRequest("aaa", "bbb",
new String(Base64.getEncoder().encode(pdfDoc)));
ObjectMetadata metadata = new ObjectMetadata();
metadata.setContentType("application/pdf");
metadata.setContentLength(pdfDoc.length);
request.setMetadata(metadata);
s3Client.putObject(request);
}
}
答案 0 :(得分:1)
要扩展@AlexGoja所说的内容,PutObjectRequest
有three constructors。 One of them采用三个字符串。但是,第三个字符串参数不是Base64编码的文件。我不确定你从哪里得到的。您要使用the constructor that takes a File上传文件:
public class App {
private static String PDF_PATH = "/tmp/pdf-test.pdf";
public static void main(String[] args) throws IOException {
// prepare AWS credential
BasicAWSCredentials awsCreds = new BasicAWSCredentials("xxx",
"yyy");
AmazonS3 s3Client = AmazonS3ClientBuilder.standard().withRegion("aaa")
.withCredentials(new AWSStaticCredentialsProvider(awsCreds)).build();
// upload a test PDF
File pdfFile = new File(PDF_PATH);
PutObjectRequest request = new PutObjectRequest("aaa", "bbb", pdfFile );
ObjectMetadata metadata = new ObjectMetadata();
metadata.setContentType("application/pdf");
metadata.setContentLength(pdfFile.length());
request.setMetadata(metadata);
s3Client.putObject(request);
}
}