如何通过HTML表单将文件上传到节点js服务器?

时间:2021-02-18 12:47:42

标签: javascript node.js xmlhttprequest file-handling

我在通过 HTML 将文件上传到节点服务器时遇到问题。在页面中我有这个输入:

<input type="file" id = "csvFile" />
<input type="submit" name="submit" onclick="send_data()" />

然后我有如下所示的 send_data 函数:

function send_data(){

    let file = document.getElementById("csvFile");
    const xhr = new XMLHttpRequest();
    xhr.open("GET", file, true);
    xhr.setRequestHeader("Content-type", "text/csv");

    xhr.onreadystatechange = () =>{

    if(xhr.readyState == XMLHttpRequest.DONE && xhr.status == 200){

        console.log("done");
    }

    xhr.send();

}

这里有第一个问题,因为就绪状态的箭头函数永远不会执行。

无论如何,这是我第一次做这样的事情,所以我不知道如何确保我的服务器获取文件并处理它。有人可以帮我吗?

1 个答案:

答案 0 :(得分:0)

这应该可以解决问题:

let file = document.getElementById("csvFile").files[0];
let xhr = new XMLHttpRequest();
let formData = new FormData();

formData.append("csvFile", file);
xhr.open("POST", '${your_full_address}');
xhr.onreadystatechange = function () {
    // In local files, status is 0 upon success in Mozilla Firefox
    if (xhr.readyState === XMLHttpRequest.DONE) {
        var status = xhr.status;
        if (status === 0 || (status >= 200 && status < 400)) {
            // The request has been completed successfully
            console.log(xhr.responseText);
        } else {
            // Oh no! There has been an error with the request!
        }
    }
};
xhr.send(formData);

参考:https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest/onreadystatechange