AJAX - The Complete Reference

(avery) #1

144 Part I: Core Ideas


Now, looking at the interesting part of the codes, some familiar ideas emerge. First,
a boundary is created.

var boundaryString = 'ajaxref';
var boundary = '--' + boundaryString;

Next, note the need for the proprietary method to read files from the local system and
deal with the fact they are binary.

var localFile = Components.classes["@mozilla.org/file/local;1"].createInstance
(Components.interfaces.nsILocalFile);

var fileStream = Components.classes["@mozilla.org/network/file-input-stream;1"]
.createInstance(Components.interfaces.nsIFileInputStream);

var bufferStream = Components.classes["@mozilla.org/network/buffered-input-
stream;1"].getService();
var binaryStream = Components.classes["@mozilla.org/binaryinputstream;1"]
.createInstance(Components.interfaces.nsIBinaryInputStream);

localFile.initWithPath( filename );
fileStream.init(localFile,0x01, 00004, null);
bufferStream.QueryInterface(Components.interfaces.nsIBufferedInputStream);
bufferStream.init(fileStream, 1000);
bufferStream.QueryInterface(Components.interfaces.nsIInputStream);
binaryStream.setInputStream (fileStream);
var binaryString = binaryStream.readBytes(binaryStream.available());

Then each file is marked with the boundary and other appropriate headers.

requestbody += boundary + '\n'
+ 'Content-Disposition: form-data; name="uploadedfile' + i + '";
filename="' + filename + '"' + '\n'
+ 'Content-Type: application/octet-stream' + '\n'
+ '\n'
+ escape(binaryString)
+ '\n';
requestbody += boundary;

When the packet is ready to be sent using the XHR, the standard approach will be modified
slightly. First, the method must always be set to POST; second, the Content-Type header is set
to be multipart/form-data and the appropriate boundary string is indicated. The Content-
length header is set to the number of bytes in the transmission. The connection is managed by
providing a header to indicate the connection should be closed so the server knows that
everything has been included. Finally, the request is sent off as usual.

// do the Ajax request
xhr.open("POST", url, true);
xhr.setRequestHeader("Content-type", "multipart/form-data; \
boundary=\"" + boundaryString + "\"");
xhr.setRequestHeader("Connection", "close");
xhr.setRequestHeader("Content-length", requestbody.length);
xhr.send(requestbody);
Free download pdf