尝试将文件上传到Amazon S3时返回错误代码400

时间:2019-03-19 23:55:29

标签: java amazon-s3

我是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);
}

}

1 个答案:

答案 0 :(得分:1)

要扩展@AlexGoja所说的内容,PutObjectRequestthree constructorsOne 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);
}

}