【问题标题】:How to upload a file to a node js server via HTML form?如何通过 HTML 表单将文件上传到节点 js 服务器?
【发布时间】:2021-02-18 12:47:42
【问题描述】:

我在通过 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();

}

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

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

【问题讨论】:

    标签: javascript node.js xmlhttprequest file-handling


    【解决方案1】:

    这应该可以解决问题:

    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

    【讨论】:

      猜你喜欢
      • 2011-04-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-01-16
      • 2012-09-28
      • 1970-01-01
      相关资源
      最近更新 更多