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

时间:2018-04-08 11:46:57

标签: javascript client-server filereader

我想通过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等于""。

4 个答案:

答案 0 :(得分:0)

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

答案 1 :(得分:0)

试试这个:

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

答案 2 :(得分:0)

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

答案 3 :(得分:0)

这就是我应该做的:

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