系统相关
首页 > 系统相关> > 在Windows Metro javascript app中读取文件

在Windows Metro javascript app中读取文件

作者:互联网

这是读取filepicker选择的文件内容的正确方法吗?我需要读取图像数据,以便将其发送到我的Windows Metro Javascript应用程序中的Web服务.我使用带有回调的readFile函数返回一个evt参数,然后使用encodeURIComponent(evt.target.result):

document.getElementById("btnUpload").onclick = function () {
            var input = document.getElementById("file_input");
            readFile(input.files[0], function(file, evt)
            {
                WinJS.xhr({
                    type: "post",
                    url: "http://servlett.domain.com:8080/Servlet/addImage",
                    headers: { "Content-type": "application/x-www-form-urlencoded" },
                    data: "fk_floor_id=" + currentFloorId + "&map=" + encodeURIComponent(evt.target.result)
                }).then(
                    function (xhr) {
                        var success = xhr.response;
                        }, function (xhr) {
                        var error = xhr.response;
                    }
                );
            }); 

通过以下方法检索参数evt.target.result:

function readFile(file, callback) {
var reader = new FileReader();
reader.onload = function (evt) {
    if (typeof callback == "function")
        callback(file, evt);
};
reader.readAsText(file);

}

其中file_input是以下形式中的输入组件:

<form action="" method="post">
        <input type="file" id="file_input" />
        <button type="button" id="btnUpload">Upload</button>
    </form>

提前致谢.

解决方法:

更好的解决方案是:

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);
           });

 });

标签:winjs,javascript,html5,windows-8,microsoft-metro
来源: https://codeday.me/bug/20191002/1844265.html