用Java编写图像的Base64显然是错误的,我错过了什么?

时间:2012-06-20 12:27:37

标签: java encoding base64

我正在尝试将来自我的Java代码的Base64编码图像发布到网站。我已经在本地对该文件进行了编码和解码测试,效果很好!但是当它进入网站时,我被告知图像是空白的。

以下是我的帖子。如果我使用其他操作而不是上传,我会得到正确的回复!

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来自以下代码:

    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);

说真的,我做错了什么?我一直在墙上撞了好几个小时了!

2 个答案:

答案 0 :(得分:3)

我终于明白了。以下是我为其他任何有此问题的人所做的事情。

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);

答案 1 :(得分:1)

FileInputStream.read(byte[] b)不保证即使数据可用,字节数组缓冲区b也将完全填满。以下代码可确保缓冲区已满。

File file = new File("temp.jpg");

FileInputStream fin = new FileInputStream(file);

byte fileContent[] = new byte[(int)file.length()];
int offset = 0;

while ( offset < fileContent.length ) {
    int count = fin.read(fileContent, offset, fileContent.length - offset);
    offset += count;
}

//all chars in encoded are guaranteed to be 7-bit ASCII
byte[] encoded = Base64.encodeBase64(fileContent);
String encodedFile = new String(encoded);

或者,您可以像这样使用ByteArrayOutputStream

File file = new File("temp.jpg");

FileInputStream fin = new FileInputStream(file);
ByteArrayOutputStream baos = new ByteArrayOutputStream();

byte [] buffer = new byte[1024];
int count = 0;

while ( (count = fin.read(buffer)) != -1 ) {
    baos.write(buffer, 0, count);
}

byte [] fileContent = baos.toByteArray();

//all chars in encoded are guaranteed to be 7-bit ASCII
byte[] encoded = Base64.encodeBase64(fileContent);
String encodedFile = new String(encoded);

或者,您可以将FileInputStream对象包装在DataInputStream对象中,如下所示:

File file = new File("temp.jpg");

FileInputStream fin = new FileInputStream(file);
DataInputStream dis = new DataInputStream(fin);

byte fileContent[] = new byte[(int)file.length()];
dis.readFully(fileContent);

//all chars in encoded are guaranteed to be 7-bit ASCII
byte[] encoded = Base64.encodeBase64(fileContent);
String encodedFile = new String(encoded);

我确信有更多方法可以完成这项工作。