- By Marcio Galli
- Applies to: DOM, XML, JavaScript, XMLHTTPRequest, Firefox/Mozilla, UTF-8
Introduction
There are cases where you may need to post via XMLHTTPRequest and format the encoded data ( sending images and form data for example ). The XMLHTTPRequest.send method allows you to post data passing a DOMDocument or passing an input stream. The second approach is useful when you want to send multiple items, for example when you want to add an image to the stream.
The following code snippet shows an example of a text string that is passed to the input stream:
var inputStream = Components.classes["@mozilla.org/io/string-input-stream;1"].createInstance(Components.interfaces.nsIStringInputStream); inputStream.setData(this.text, -1);
With the above approach, if the Document ( being this.text ) has UTF-8 then special characters will be cut. To ensure that your stream has UTF-8 you need to convert and use a stream from the converter.
Converting to UTF-8
The converter allows you get an inputStream directly from it:
var converter = Components.classes["@mozilla.org/intl/scriptableunicodeconverter"]
.createInstance(Components.interfaces.nsIScriptableUnicodeConverter);
converter.charset = "UTF-8";
var obj1New = converter.convertToInputStream(requestBody.toString());
Sending data with the send method
The following example shows how the above stream was appended to another stream which represents the entire set to be sent:
objmulti.appendStream(obj1New ); objmulti.appendStream(image); objmulti.appendStream(obj3); req.send(objmulti);
objmulti uses the nsIMultiplexInputStream:
var objmulti = Components.classes["@mozilla.org/io/multiplex-input-stream;1"]. createInstance(Components.interfaces.nsIMultiplexInputStream);
and req is the XMLHTTPRequest object. It has to be initialized in POST mode.
req = new XMLHttpRequest();
req.open('POST', URILocation, true);
