【问题标题】:Read the content of file with FileReader and send it via ajax使用 FileReader 读取文件内容并通过 ajax 发送
【发布时间】:2018-04-08 11:46:56
【问题描述】:

我想通过 ajax 将文件的内容发送到我的服务器端。 我正在使用 FileReader 在客户端读取文件并将其发送到我的服务器端,如下所示:

function readFile(file) {
  var content = "";
  var reader = new FileReader();

  reader.onload = function(e) {
     content = reader.result;
     console.log(content);
  }

  console.log(content);

  reader.readAsText(file);
  return content;
}

var data = {};
data.content = readFile(file);
data.surname = surname;
data.first = firstname;

console.log(data);
sendData(data, global_url + '/instance');

function sendData(data, url) {
    console.log("Try to send the data");
    $.ajax({
        type: 'POST',
        data: JSON.stringify(data),
        contentType: 'application/json',
        url: url,
        success: function (data) {
            console.log('success');
            console.log(JSON.stringify(data));
            if (data === 'done')
            {
                window.location.href = "/";
            } else {
                alert('Error');
            }
        },
        error: function () {
            console.log('process error');
        }
    });
}

但是,我不知道如何返回变量。 函数 readFile 中的第二个 console.log 等于 ""。

【问题讨论】:

  • reader.onload 是async,所以console.log(content); 是""
  • 好的,可以返回内容吗? @xianshenglu
  • 将sendData(data, global_url + '/instance'); 放入readFile()。
  • 如果没有,有没有办法删除异步?做一个同步函数?@AjAX.

标签: javascript client-server filereader


【解决方案1】:

onload 方法是异步的,因此您必须等待它准备好。您可以更改代码以使用 Promise 或简单的回调:

function readFile(file, cb) { // We pass a callback as parameter
    var content = "";
    var reader = new FileReader();

    reader.onload = function(e) {
        content = reader.result;
        // Content is ready, call the callback
        cb(content);
    }

    reader.readAsText(file);
    // return content; This is not needed anymore
}

var data = {};

readFile(file, function(content) {
    data.content = content;
    data.surname = surname;
    data.first = firstname;
    sendData(data, global_url + '/instance');
})

function sendData(data, url) {
    console.log("Try to send the data");
    $.ajax({
        type: 'POST',
        data: JSON.stringify(data),
        contentType: 'application/json',
        url: url,
        success: function (data) {
            console.log('success');
            console.log(JSON.stringify(data));
            if (data === 'done')
            {
                window.location.href = "/";
            } else {
                alert('Error');
            }
        },
        error: function () {
            console.log('process error');
        }
    });
}

这样你调用readFile函数,一旦它准备好返回数据,你就可以调用sendData方法

【讨论】:

    【解决方案2】:

    试试这个:

    function readFile(file) {
        var content = "";
        var reader = new FileReader();
    
        reader.onload = function (e) {
            var data = {};
            content = reader.result;
            console.log(content);
            data.content = readFile(file);
            data.surname = surname;
            data.first = firstname;
            sendData(data, global_url + '/instance');
        }
    
        //console.log(content);
    
        reader.readAsText(file);
        return content;
    }
    readFile(file);
    
    // console.log(data);
    
    function sendData(data, url) {
        console.log("Try to send the data");
        $.ajax({
            type: 'POST',
            data: JSON.stringify(data),
            contentType: 'application/json',
            url: url,
            success: function (data) {
                console.log('success');
                console.log(JSON.stringify(data));
                if (data === 'done') {
                    window.location.href = "/";
                } else {
                    alert('Error');
                }
            },
            error: function () {
                console.log('process error');
            }
        });
    }
    

    如果需要,可以使用 es6 promise 或 async

    【讨论】:

      【解决方案3】:

      reader.onload 是异步函数,因此无法通过 variable = readFileFunction() 获取值 但是你可以做的是使用回调或承诺来获取文件内容

      例子: 回调:

          function readFile(file, callback) {
          var content = "";
          var reader = new FileReader();
      
          reader.onload = function(e) {
              content = reader.result;
              if (callback){
                  callback(reader.result); // that will call your call back function
              }
              console.log(content);
          }
      
          console.log(content);
      
          reader.readAsText(file);
          return content;
      }
      
      var data = {};
      readFile(file, function (content) { // call this function from readFile function
          data.content = content;
          data.surname = surname;
          data.first = firstname;
      
          console.log(data);
          sendData(data, global_url + '/instance');
      
      });
      
      function sendData(data, url) {
          console.log("Try to send the data");
          $.ajax({
              type: 'POST',
              data: JSON.stringify(data),
              contentType: 'application/json',
              url: url,
              success: function (data) {
                  console.log('success');
                  console.log(JSON.stringify(data));
                  if (data === 'done')
                  {
                      window.location.href = "/";
                  } else {
                      alert('Error');
                  }
              },
              error: function () {
                  console.log('process error');
              }
          });
      }
      

      承诺:

      function readFile(file) {
          return new Promise(
              function (resolve, reject) {
                  var content = "";
                  var reader = new FileReader();
      
                  reader.onload = function(e) {
                      content = reader.result;
                      console.log(content);
                      resolve(content);
                  };
      
                  reader.onerror = function (ev) { 
                      reject("reading failed");
                  };
      
                  reader.readAsText(file);
              }
          );
      }
      
      readFile(file).then(function (fileContent) {
          var data = {};
          data.content = fileContent;
          data.surname = surname;
          data.first = firstname;
      
          console.log(data);
          sendData(data, global_url + '/instance');
      
      });
      
      function sendData(data, url) {
          console.log("Try to send the data");
          $.ajax({
              type: 'POST',
              data: JSON.stringify(data),
              contentType: 'application/json',
              url: url,
              success: function (data) {
                  console.log('success');
                  console.log(JSON.stringify(data));
                  if (data === 'done')
                  {
                      window.location.href = "/";
                  } else {
                      alert('Error');
                  }
              },
              error: function () {
                  console.log('process error');
              }
          });
      }
      

      【讨论】:

      • 读取文件作为 promise 的技巧:new Response(file).text().then(console.log)
      【解决方案4】:

      这是我应该做的:

      <form action="/upload" method="post" enctype="multipart/form-data">
        <input type="file" name="file" accept="text/*">
        <input type="text" name="surename" autocomplete="family-name">
        <input type="text" name="firstname" autocomplete="given-name">
        <input type="submit">
      </form>
      
      <script>
      jQuery($ => {
        $('form').submit(async evt => {
          evt.preventDefault()
          const form = evt.target
          const fd = new FormData(form)
      
          const res = await fetch(form.action, {
            method: form.method,
            body: fd
          })
      
          if (res.ok) {
            const json = await res.json()
            console.log(json)
          } else {
            alert('Error')
          }
        })
      })
      </script>
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-09-16
        • 2022-10-24
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多