它可能是重复的,但我在将图像转换为时遇到一些问题Base64
发送给Http Post
。我已经尝试过这段代码,但它给了我错误的编码字符串。
public static void main(String[] args) {
File f = new File("C:/Users/SETU BASAK/Desktop/a.jpg");
String encodstring = encodeFileToBase64Binary(f);
System.out.println(encodstring);
}
private static String encodeFileToBase64Binary(File file){
String encodedfile = null;
try {
FileInputStream fileInputStreamReader = new FileInputStream(file);
byte[] bytes = new byte[(int)file.length()];
fileInputStreamReader.read(bytes);
encodedfile = Base64.encodeBase64(bytes).toString();
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return encodedfile;
}
Output:[B@677327b6
但我将同一张图像转换为Base64
在许多在线编码器中,它们都给出了正确的大 Base64 字符串。
Edit:怎么是重复的??与我重复的链接没有给我转换我想要的字符串的解决方案。
我在这里缺少什么?
问题是你正在返回toString()
的呼叫Base64.encodeBase64(bytes)
它返回一个字节数组。所以你最终得到的是字节数组的默认字符串表示形式,它对应于你得到的输出。
相反,你应该这样做:
encodedfile = new String(Base64.encodeBase64(bytes), "UTF-8");
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)