10

In order to upload a binary file to an URL, I have been advised to use this guide. However, the file is not in a directory, but is stored in a BLOB field in MySql db. The BLOB field is mapped as a byte[] property in JPA:

byte[] binaryFile;

I have slightly modified the code taken from the guide, in this way:

HttpURLConnection connection = (HttpURLConnection ) new URL(url).openConnection();
// set some connection properties
OutputStream output = connection.getOutputStream();
PrintWriter writer = new PrintWriter(new OutputStreamWriter(output, CHARSET), true); 
// set some headers with writer
InputStream file = new ByteArrayInputStream(myEntity.getBinaryFile());
System.out.println("Size: " + file.available());
try {
    byte[] buffer = new byte[4096];
    int length;
    while ((length = file.read(buffer)) > 0) {
        output.write(buffer, 0, length);
    } 
    output.flush();
    writer.append(CRLF).flush();
    writer.append("--" + boundary + "--").append(CRLF).flush();
} 
// catch and close streams

I am not using chunked streaming. The headers used are:

username and password
Content-Disposition: form-data; name=\"file\"; filename=\"myFileName\"\r\nContent-Type: application/octet-stream"
Content-Transfer-Encoding: binary

All the headers are received correctly by the host. It also receives the uploaded file, but unfortunately complains that the file is not readable, and asserts that the size of the received file is 37 bytes larger than the size outputed by my code.

My knowledge of streams, connections and byte[] is too limited for grasping the way to fix this. Any hints appreciated.


EDIT

As suggested by the commenter, I have tried also to write the byte[] directly, without using the ByteArrayInputStream:

output.write(myEntity.getBinaryFile());

Unfortunately the host gives exactly the same answer as the other way.

Community
  • 1
  • 1
perissf
  • 15,979
  • 14
  • 80
  • 117
  • Why are you streaming the file through a BAIS? Why not just write directly from the byte array itself? – Jim Garrison Nov 20 '12 at 19:00
  • What happens if instead of using `file.available()` you do `byte[] temp = myEntity.getBinaryFile();` and use `temp.length`? I suspect `file.available()` is off. – Jim Garrison Nov 20 '12 at 20:40
  • In this case, file.available() was accurate, giving the exact number of bytes. I have just solved the issue: using the hint that there were too many bytes in the file received by the host, I removed the Content-Transfer-Encoding header, and an end-line, and now it's OK. Thanks for the help anyway! – perissf Nov 20 '12 at 20:56

1 Answers1

6

My code was correct.

The host was giving an error because it didn't expect the Content-Transfer-Encoding header. After removing it, everything went fine.

perissf
  • 15,979
  • 14
  • 80
  • 117