Note that there are some explanatory texts on larger screens.

plurals
  1. POHow to upload binary file using URLConnection
    primarykey
    data
    text
    <p>In order to upload a binary file to an URL, I have been advised to use <a href="https://stackoverflow.com/a/2793153/870122">this guide</a>. 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 <code>byte[]</code> property in JPA:</p> <pre><code>byte[] binaryFile; </code></pre> <p>I have slightly modified the code taken from the guide, in this way:</p> <pre><code>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)) &gt; 0) { output.write(buffer, 0, length); } output.flush(); writer.append(CRLF).flush(); writer.append("--" + boundary + "--").append(CRLF).flush(); } // catch and close streams </code></pre> <p>I am not using chunked streaming. The headers used are:</p> <pre><code>username and password Content-Disposition: form-data; name=\"file\"; filename=\"myFileName\"\r\nContent-Type: application/octet-stream" Content-Transfer-Encoding: binary </code></pre> <p>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.</p> <p>My knowledge of streams, connections and byte[] is too limited for grasping the way to fix this. Any hints appreciated.</p> <hr> <p>EDIT</p> <p>As suggested by the commenter, I have tried also to write the byte[] directly, without using the ByteArrayInputStream:</p> <pre><code>output.write(myEntity.getBinaryFile()); </code></pre> <p>Unfortunately the host gives exactly the same answer as the other way.</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload