I'm trying to upload a file via URLConnection, but I need to read/write it as a binary file without any encoding changes.
So i've tried to read byte[]
array from a FileInputStream
, but now i have an issue. The PrintWriter
object I use for outputing to the server does not allow me to do writer.write(content)
(where content
is of type byte[]
). How can i fix this? Or is there another way to quickly copy binary data from a FileInputStream
to a PrintWriter
?
Thank you
I bet that this is an follow-up on this question: Upload files from Java client to a HTTP server
If you want to upload binary files as well using multipart/form-data
, then you need to write them to the OutputStream
instead. Here's the changed example of the code as I posted in your previous example, only the try
block has been changed to keep a separate handle to the binary output stream, so that you can write any InputStream
s to it without any encoding pains:
OutputStream output = null;
PrintWriter writer = null;
try {
output = connection.getOutputStream();
writer = new PrintWriter(new OutputStreamWriter(output, "UTF-8"), true); // true = Autoflush, important!
writer.println("--" + boundary);
writer.println("Content-Disposition: form-data; name=\"paramToSend\"");
writer.println("Content-Type: text/plain; charset=UTF-8");
writer.println();
writer.println(paramToSend);
writer.println("--" + boundary);
writer.println("Content-Disposition: form-data; name=\"fileToUpload\"; filename=\"" + fileToUpload.getName() + "\"");
writer.println("Content-Type: " + URLConnection.guessContentTypeFromName(fileToUpload.getName());
writer.println("Content-Transfer-Encoding: binary");
writer.println();
InputStream input = null;
try {
input = new FileInputStream(fileToUpload);
byte[] buffer = new byte[1024];
for (int length = 0; (length = input.read(buffer)) > 0;) {
output.write(buffer, 0, length);
}
output.flush();
} finally {
if (input != null) try { input.close(); } catch (IOException logOrIgnore) {}
}
writer.println();
writer.println("--" + boundary + "--");
} finally {
if (writer != null) writer.close();
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With