使用 FileReader 读取文件内容并通过 ajax 发送

Read the content of file with FileReader and send it via ajax

我想通过 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');
        }
    });
}

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

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

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 函数,一旦它准备好它 returns 数据,你就可以调用 sendData 方法

试试这个:

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 promiseasync

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

这是我应该做的:

<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>