AWS Lambda 和 S3 - 上传的 pdf 文件是空白的

Lla*_*ama 3 java spring amazon-s3 amazon-web-services aws-lambda

我有一个非常简单的函数,可以使用 AWS Lambda 和 Amazon API Gateway将 PDF 文件上传到 AWS S3 ( https://codedestine.com/aws-s3-putobject-java/ )。

我尝试上传一个包含 2 页文本的 PDF 文件。上传后,PDF 文件(在 AWS S3 上)有 2 个空白页。

这是我用来在 AWS S3 上上传 PDF 文件的方法。

public static void uploadFile2(MultipartFile mpFile, String fileName) throws IOException{
   
    String dirPath = System.getProperty("java.io.tmpdir", "/tmp");
    File file = new File(dirPath  + "/" + fileName);

    OutputStream ops = new FileOutputStream(file);
    ops.write(mpFile.getBytes());

    s3client.putObject("fakebucketname", fileName, file);

}
Run Code Online (Sandbox Code Playgroud)

为什么上传的PDF文件是空白的?

Lla*_*ama 5

事实证明,这将做到这一点。感谢@KunLun 的帮助,这一切都与编码有关。在我的场景中,文件是通过 POST 传递给 aws 到 url 的多部分文件 (pdf)。


            Base64.Encoder enc = Base64.getEncoder();
            byte[] encbytes = enc.encode(file.getBytes());
            for (int i = 0; i < encbytes.length; i++)
            {
                System.out.printf("%c", (char) encbytes[i]);
                if (i != 0 && i % 4 == 0)
                    System.out.print(' ');
            }
            Base64.Decoder dec = Base64.getDecoder();
            byte[] barray2 = dec.decode(encbytes);
            InputStream fis = new ByteArrayInputStream(barray2);
    
            PutObjectResult objectResult = s3client.putObject("xxx", 
            file.getOriginalFilename(), fis, data);


Run Code Online (Sandbox Code Playgroud)

另一个非常重要的部分是必须正确配置 API 网关设置以支持二进制数据类型。AWS 控制台 --> API 网关 --> 设置 --> 在所附照片中包含我下面的内容