【问题标题】:Convert files to base64 string to send as attachment through android application将文件转换为 base64 字符串以通过 android 应用程序作为附件发送
【发布时间】:2016-06-10 15:16:55
【问题描述】:

我创建了一个应用程序,在其中我使用 mandrill 应用程序 API 发送电子邮件。正在发送没有附件的电子邮件,但是当我将图像附加到它时,它会在接收方接收为损坏的图像。这里需要将文件转换为base64字符串以传入json数组。我使用了这段代码:

public static String encodeImagetoBase64(Bitmap img) {
    Bitmap image = img;
    ByteArrayOutputStream byteOStream = new ByteArrayOutputStream();
    image.compress(Bitmap.CompressFormat.JPEG, 100, byteOStream);
    byte[] b = byteOStream.toByteArray();
    String imageEncoded = Base64.encodeToString(b, Base64.DEFAULT);
    Log.e("Look", imageEncoded);
    return imageEncoded;

}

那么谁能告诉我解决方案,为什么图像会损坏。 同样,我也想将扩展名为“.txt、.doc、.docx、.pptx、.pdf、.xls”等的文件转换为附件,所以请向我推荐任何来源。谢谢

【问题讨论】:

  • 您是否尝试使用 Base64.URL_SAFE 而不是 Base64.DEFAULT? “接收方”如何处理您的图像?
  • 这是随机颜色的东西,Base64.URL_SAFE我没试过,我试一下告诉你,
  • URL_SAFE 在网络上传输数据时常用,它与 DEFAULT 实现略有不同,更可能被 Mandrill 使用,您可以在相关RFC4648 中阅读更多理论。跨度>
  • 它不能解决问题。在使用 URL_SAFE 之前,可以看到一些扭曲/损坏的(随机颜色的图像)图像,但现在它不显示任何图像
  • 出于纯粹的兴趣,您可以粘贴使用 DEFAULT 时的失真样本吗?是像白噪声还是相同的图像,但损坏了?

标签: android base64 email-attachments


【解决方案1】:

我正在使用这种方法并且它正在工作:

 public static String getFileBinary(String uploadFilePath) {
        String encodedString = "0";
        if (uploadFilePath.length() < 2)
            return encodedString;
        try {
            InputStream inputStream = new FileInputStream(uploadFilePath);//You can get an inputStream using any IO API
            byte[] bytes;
            byte[] buffer = new byte[8192];
            int bytesRead;
            ByteArrayOutputStream output = new ByteArrayOutputStream();
            try {
                while ((bytesRead = inputStream.read(buffer)) != -1) {
                    output.write(buffer, 0, bytesRead);

                }
            } catch (IOException e) {
                e.printStackTrace();
            }
            bytes = output.toByteArray();
            encodedString = Base64.encodeToString(bytes, Base64.DEFAULT);

        } catch (IOException es) {

        }
        return encodedString;
    }

【讨论】:

  • 现在我收到了除 .txt 文件之外的附件。但我得到的其他文件没有扩展名。并且名称为“noname”..在收件箱中,只有pdf文件的内容可见,但下载后没有扩展名。
  • 当然。这仅用于获取文件的二进制数据,对于通过 Mandrill 发送附件,您还需要提及文件名和文件扩展名。
  • 哦……那我该怎么做……??
  • 我无法上传,因为我没有足够的声望点。扭曲的图像就像一层层的图像
  • 我刚刚发给你的链接是在山魈网站上找到的官方链接,我想如果你检查它足够好你可以在那里找到你的答案。除此之外,我很抱歉我不能帮助你。
猜你喜欢
  • 2023-01-07
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-03-09
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多