有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

从Gcloud存储下载的java图像或Pdf文件已损坏

我使用从Gcloud存储下载的文件作为Mandrill API的附件,以电子邮件附件的形式发送。问题是它只适用于文本文件,但对于图像或Pdf,附件已损坏 以下代码用于下载文件并将其转换为Base64编码字符串

Storage.Objects.Get getObject = getService().objects().get(bucket, object);

    ByteArrayOutputStream out = new ByteArrayOutputStream();
    // If you're not in AppEngine, download the whole thing in one request, if possible.
    getObject.getMediaHttpDownloader().setDirectDownloadEnabled(true);
    getObject.executeMediaAndDownloadTo(out);
    //log.info("Output: {}", out.toString("UTF-8"));
    return Base64.encodeBase64URLSafeString(out.toString("UTF-8")
        .getBytes(StandardCharsets.UTF_8));

我正在Mandrill API的MessageContent内容中设置这个字符串


共 (1) 个答案

  1. # 1 楼答案

    成功了。我只需要将OutputStream存储在一个临时文件中,然后将其作为电子邮件附件使用。发布下面的代码以供参考

    Storage.Objects.Get getObject = storage.objects().get("bucket", "object");
    
    OutputStream out = new FileOutputStream("/tmp/object");
    // If you're not in AppEngine, download the whole thing in one request, if possible.
    getObject.getMediaHttpDownloader().setDirectDownloadEnabled(true);
    getObject.executeMediaAndDownloadTo(out);