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.
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 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!
FileInputStream.read(byte[] b)
does not guarantee that the byte array bufferb
will be completely filled even if the data is available. The following code ensures the buffer is completely full.Alternatively, you could use
ByteArrayOutputStream
like this:Or, you could wrap your
FileInputStream
object in aDataInputStream
object like this:I'm sure there are more ways to get this done.
I finally figured it out. Here is what I did for anyone else having this issue.