Is this the right way to read the content of a file picked by a filepicker? I need to read the image data in order to send it to a webservice in my Windows Metro Javascript
There are few issues here:
input type="file"
will not give native look and feel in the app for picking an image. Instead is good to pick and preview image on the lines of this msdn walk through. Along with this, the upload WinJS.xhr
call will look little different.
There are other requirements that might be relevant in the scenario e.g. showing preview of the uploaded image to the web service. I have to take care of many other requirements for our winjs application when uploading image to the service. This post might be relevant for you for code listing and thinking about this holistically.
A better solution is:
var picker = new Windows.Storage.Pickers.FileOpenPicker();
picker.fileTypeFilter.replaceAll([".jpg", ".bmp", ".gif", ".png"]);
picker.pickSingleFileAsync().then(progressResults, displayError);
function progressResults(file) {
file.openAsync(Windows.Storage.FileAccessMode.read).done(function (stream) {
var inputStream = stream.getInputStreamAt(0);
var reader = new Windows.Storage.Streams.DataReader(inputStream);
var size = stream.size;
if (size > 0) {
reader.loadAsync(size).then(function () {
var b = reader.readBuffer(size);
var s = Windows.Security.Cryptography.CryptographicBuffer.encodeToBase64String(b);
var xhrOptions = {
type: 'post',
url: "http://servlet.domain.com:8080/Servlet/addImage",
headers: { "Content-type": "application/x-www-form-urlencoded" },
data: "fk_floor_id=" + currentFloorId + "&map=" + s
}
WinJS.xhr(xhrOptions);
});
});