将图像文件从aws s3对象转换为base64时出错

mefy6pfw  于 2021-07-24  发布在  Java
关注(0)|答案(1)|浏览(407)

我使用下面的代码将s3对象解析为base64字符串。

InputStream is = s3Object.getObjectContent().getDelegateStream();
byte[] bytes = IOUtils.toByteArray(is);
String base64Data = Base64.getEncoder().encodeToString(bytes); //Java Util lib.

这段代码适用于文本和pdf文件。但在转换图像文件时,我得到一个错误mime类型不受支持。
我还尝试使用aws和apachecommons base64 lib。但它仍然不起作用。

Base64.encodeAsString(bytes) //AWS
Base64.encodeBase64String(bytes) //Apache Commons
zphenhs4

zphenhs41#

aws java sdk 2

import software.amazon.awssdk.regions.Region;
import software.amazon.awssdk.services.s3.S3Client;
import software.amazon.awssdk.services.s3.model.GetObjectRequest;

import java.io.IOException;

public class S3ReadImg {
    public static void main(String[] args) throws IOException {

        S3Client s3 = S3Client.builder()
                .region(Region.EU_WEST_1) //
                .build(); // Might change for you

        GetObjectRequest getObjectRequest = GetObjectRequest.builder()
                .bucket("my_bucket_name")
                .key("four.bmp") // also tested for image types png, jpg, gif
                .build();

        byte[] objectResponse = s3.getObject(getObjectRequest).readAllBytes();

        String encodedfile = new String(java.util.Base64.getEncoder().encode(objectResponse), java.nio.charset.StandardCharsets.UTF_8);

    }
}

相关问题