1

我必须从应用程序的本地内存上传一个文件(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);
});

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

4

0 回答 0