Java Reference
In-Depth Information
How it works...
As mentioned earlier, as of version 1.2 of the SDK, JavaFX does not currently have a direct
way to upload a file to a web server using the HttpRequest object. However, in this recipe
we have manually crafted a multi-part form stream at the HTTP protocol level to achieve a file
upload. Here is how the code snippet works:
F Firstly, the snippet declares a series of constants ( MARKER , CRLF , BOUNDARY , and
CONTENT_TYPE ) that are used to construct the multi-part form header and footer
byte sequences.
F Next, the code defines the utility class FormPart , which exposes a method that
is used to assemble the multi-part form byte stream that is sent to the server. The
function writeToFile(out:java.io.OutputStream) of that class will arrange
the data by laying out the header marker bytes followed by the bytes of the file being
uploaded into the output stream.
F The code then declares an instance of HttpRequest , used to communicate with the
server for the file upload. The code sets the location and the method properties
for the request.
F HttpRequest.headers —in the HttpRequest declaration, we are providing
header information using the headers property. You can define one or more request
headers, which will be sent to the server as metadata about the request. In our code,
we send header CONTENT_TYPE to indicate the type of content (multi-part form) the
server should expect.
F We define an event-handler function for property HttpRequest.onOutput to write
the outgoing bytes to the server. In it, we do the following:
FormPart —we use an instance of FormPart to generate the byte
sequence for the multi-part boundaries and markers needed for
the file upload header information. Then, the content of the file is
opened using a FileInputStream instance, whose binary stream
content is written to OutputStream being set to the server through
the out.write(byte[]) call.
footer —to close out the stream, the code applies footer markers,
through the variable footer , to signal the end of the multi-part
binary submission to the OutputSream instance.
There's more...
You can read more about the topics discussed here:
F Multi-Part Message— http://en.wikipedia.org/wiki/MIME
F Java IO Tutorial— http://java.sun.com/docs/books/tutorial/essential/
io/
 
Search WWH ::




Custom Search