Base64编码的图像在Java中显然是错误的,我还缺少什么? [英] Base64 encoding a image in Java wrong apparently, what am I missing?
问题描述
我正在尝试将Base64编码的图像从我的Java代码发布到网站。我已经测试编码和解码的文件在本地,它的工作非常好!但是当它到达网站时,我被告知图像是空白的。
I am attempting to POST a Base64 encoded image from my Java code to a website. I have tested encoding and decoding the file locally and it works great! However when it gets to the website, I am told the image is blank.
这是我的POST。如果我使用另一个动作而不是上传,我会得到正确的响应!
Here is how I am POST'ing. If I used another action instead of upload, I get the correct response!
ready = new java.net.URL(url);
WebRequest request = new WebRequest(ready, HttpMethod.POST);
request.setAdditionalHeader("Content-Type", "application/x-www-form-urlencoded");
String requestBody = "action=upload"
+"&key=ABCDEFG123456"
+ "&file=" + encodedFile
+ "&gen_task_id=" + SQL.getNextID();
encodedFile来自以下代码:
encodedFile comes from the following code:
File file = new File("temp.jpg");
FileInputStream fin = new FileInputStream(file);
byte fileContent[] = new byte[(int)file.length()];
fin.read(fileContent);
//all chars in encoded are guaranteed to be 7-bit ASCII
byte[] encoded = Base64.encodeBase64(fileContent);
String encodedFile = new String(encoded);
严重的是,我做错了什么?我已经在墙上殴打了几个小时了!
Seriously, what am I doing wrong?? I've been beating my head against the wall for hours now!
推荐答案
我终于弄清楚了。这是我为这个问题的任何人所做的。
I finally figured it out. Here is what I did for anyone else having this issue.
BufferedImage img = ImageIO.read(new File("temp.jpg"));
ByteArrayOutputStream baos = new ByteArrayOutputStream();
ImageIO.write(img, "jpg", baos);
baos.flush();
Base64 base = new Base64(false);
String encodedImage = base.encodeToString(baos.toByteArray());
baos.close();
encodedImage = java.net.URLEncoder.encode(encodedImage, "ISO-8859-1");
request.setRequestBody(encodedImage);
这篇关于Base64编码的图像在Java中显然是错误的,我还缺少什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!