Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to upload binary file using URLConnection

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.

like image 356
perissf Avatar asked Nov 20 '12 18:11

perissf


1 Answers

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.

like image 82
perissf Avatar answered Oct 10 '22 00:10

perissf