使用chrome中的Filereader进行Fileupload

时间:2012-09-16 21:57:49

标签: html5 xmlhttprequest filereader

我必须从应用程序的本地内存(HTML5 File api)上传文件。 Onselect,用户应该可以直接上传而不会有任何问题。我们的想法是无缝管理下载/上传到用户。这是代码:

    $("body").on("click", ".upload-file", function(e){

    var fileToUpload = $('input:radio[name=optionsRadios]:checked').val();
    var formData = new FormData();

    $('input:radio[name=optionsRadios]:checked').parent().parent().parent().remove();

    window.requestFileSystem  = window.requestFileSystem || window.webkitRequestFileSystem;      
    window.requestFileSystem(window.TEMPORARY, 50*1024*1024, initFS, errorHandler);

    var reader = new FileReader();
    function initFS(fs){
        fs.root.getDirectory('/', {}, function(dirEntry){
            var dirReader = dirEntry.createReader();
            dirReader.readEntries(function(entries) {
                for(var key = 0; key < entries.length; key++) {
                        var entry = entries[key];
                         if (entry.isFile){
                             var name = entry.name;                             
                             if(name == fileToUpload){
                                 getAsText(entry.toURL());
                                 formData.append('file', entry.toURL);
                                 break;
                             }
                        }
                }

        }, errorHandler);
        }, errorHandler);
    }

    function errorHandler(){
          console.log('An error occured');
        }   

    function getAsText(readFile) {
          alert ("getting as text :" +readFile);
          var reader = new FileReader();

          // Read file into memory as UTF-16      
          reader.readAsText(readFile, "UTF-16");

          // Handle progress, success, and errors
          reader.onprogress = updateProgress;
          reader.onload = loaded;
          reader.onerror = errorHandler;
    }

    function loaded(evt) {  
          // Obtain the read file data 
            alert("loaded file");
          var fileString = evt.target.result;
          // Handle UTF-16 file dump
          if(utils.regexp.isChinese(fileString)) {
            //Chinese Characters + Name validation
          }
          else {
            // run other charset test
          }
          // xhr.send(fileString)     
        }
    var serverurl = "/fileserver/uploadFile?selpath="+fileToUpload;       

      var xhr = new XMLHttpRequest();
      xhr.open('POST', serverurl);
      xhr.onload = function () {
        if (xhr.status === 200) {
          console.log('all done: ' + xhr.status);
        } else {
          console.log('Something went terribly wrong...');
        }
      };

      xhr.send(formData);
});

现在,我正在尝试将文件作为文本读取(这是一个不好的做法,但想要找到它使其工作),但它不会抛出任何事件。你能帮我找一下我错的地方吗?

0 个答案:

没有答案