2

我正在尝试将我的 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);

说真的,我做错了什么??我已经用头撞墙了好几个小时了!

4

2 回答 2

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);
于 2012-06-20T13:29:22.183 回答
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);

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

于 2013-03-06T18:10:22.460 回答