繁体   English   中英

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

[英]How to upload a file to a node js server via HTML form?

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

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

然后我有如下所示的 send_data function:

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();

}

这里出现了第一个问题,因为就绪的 state 的箭头 function 永远不会执行。

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

这应该可以解决问题:

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM