[英]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.