Java 如何正确打开png文件
我正在尝试附加png文件。目前,当我发送电子邮件时,附件比文件应该大2倍,并且是无效的png文件。以下是我目前拥有的代码:Java 如何正确打开png文件,java,Java,我正在尝试附加png文件。目前,当我发送电子邮件时,附件比文件应该大2倍,并且是无效的png文件。以下是我目前拥有的代码: import com.sendgrid.*; Attachments attachments = new Attachments(); String filePath = "/Users/david/Desktop/screenshot5.png"; String data = ""; try { data = ne
import com.sendgrid.*;
Attachments attachments = new Attachments();
String filePath = "/Users/david/Desktop/screenshot5.png";
String data = "";
try {
data = new String(Files.readAllBytes(Paths.get(filePath)));
} catch (IOException e) {
}
byte[] encoded = Base64.encodeBase64(data.getBytes());
String encodedString = new String(encoded);
attachments.setContent(encodedString);
也许我对数据的编码不正确?“获取”数据以附加它的正确方法是什么?恕我直言,这就是为什么Python给现代开发人员带来了一个问题。它抽象掉了在解释语言中无法完全理解的重要概念 首先,这是一个相对基本的概念,但是你。以下是您的第一个问题:
data = new String(Files.readAllBytes(Paths.get(filePath)));
编辑:看起来您正在使用的库需要对文件进行base64编码。我不知道为什么。尝试将代码更改为:
Attachments attachments = new Attachments();
String filePath = "/Users/david/Desktop/screenshot5.png";
try {
byte[] encoded = Base64.encodeBase64(Files.readAllBytes(Paths.get(filePath)));
String encodedString = new String(encoded);
attachments.setContent(encodedString);
} catch (IOException e) {
}
您遇到的唯一问题是,您试图将任意字节表示为字符串。恕我直言,这就是为什么Python会给现代开发人员带来问题的原因。它抽象掉了在解释语言中无法完全理解的重要概念 首先,这是一个相对基本的概念,但是你。以下是您的第一个问题:
data = new String(Files.readAllBytes(Paths.get(filePath)));
编辑:看起来您正在使用的库需要对文件进行base64编码。我不知道为什么。尝试将代码更改为:
Attachments attachments = new Attachments();
String filePath = "/Users/david/Desktop/screenshot5.png";
try {
byte[] encoded = Base64.encodeBase64(Files.readAllBytes(Paths.get(filePath)));
String encodedString = new String(encoded);
attachments.setContent(encodedString);
} catch (IOException e) {
}
您遇到的唯一问题是,您试图将任意字节表示为字符串。请查看存储库中的生成器类。例如:
FileInputStream fileContent = new FileInputStream(filePath);
Attachments.Builder builder = new Attachments.Builder(fileName, fileContent);
mail.addAttachments(builder.build());
看看存储库中的Builder类。例如:
FileInputStream fileContent = new FileInputStream(filePath);
Attachments.Builder builder = new Attachments.Builder(fileName, fileContent);
mail.addAttachments(builder.build());
谢谢你指出这一点。您能否举例说明setSourceStream在上述情况下的工作方式?在上面的示例中,我基本上是如何到达
encodedString
的?@David542为什么需要encodedString
变量?您的目标不是从PNG文件创建附件吗?是的。最后一步是设置附件的内容。@David542则不需要encodedString
变量。你只需要按照我答案最后一段的指示去做。打开PNG图像的文件流,并将其传递给附件实例的setSourceStream
。在我从Sendgrid使用的Attachments
类中,这不是可用的方法。您介意发布一些代码来显示您正在导入的内容以及如何设置它吗?那么我可以接受答案了。谢谢你指出这一点。您能否举例说明setSourceStream在上述情况下的工作方式?在上面的示例中,我基本上是如何到达encodedString
的?@David542为什么需要encodedString
变量?您的目标不是从PNG文件创建附件吗?是的。最后一步是设置附件的内容。@David542则不需要encodedString
变量。你只需要按照我答案最后一段的指示去做。打开PNG图像的文件流,并将其传递给附件实例的setSourceStream
。在我从Sendgrid使用的Attachments
类中,这不是可用的方法。您介意发布一些代码来显示您正在导入的内容以及如何设置它吗?那我就可以接受答案了。