Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
692 views
in Technique[技术] by (71.8m points)

java - 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"
Content-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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...