簡體   English   中英

發布文件是否需要<form>標簽和按鈕?

[英]Does POSTing a file require a <form> tag and button?

我在我的 webapp 的標題中有一個選項來選擇一個帶有<input type='file'/> ,我希望一旦文件被選中,它就開始將它上傳到我的本地 nodejs 服務器。

我是否需要將其封裝在具有 POST 屬性的標簽中並使用按鈕進行確認? 和/或是否可以在選擇文件而不是使用按鈕時立即調用 POSTing?

您為<input type="file" id="input"> elm 設置了一個 onchange 事件。

Javascript

let input = document.getElementById('input');
input.onchange = function(e) { 
  if (file.files.length > 1) {
     // Upload
  }
};

在選定文件的表單值存在並且我們的onchange事件被觸發之后。 然后我們使用 Fetch post 發布文件。

例子

 const input = document.getElementById('input'); function upload(file) { fetch('http://', { method: 'POST', headers: { 'Content-type': 'file-type' }, body: file }).then(() => { }).catch((error) => { // Errors console.log('Log the error, since we are demoing'); }) } let chosen = () => { try { upload(input.files[0]); } catch(error) { } } input.addEventListener('change', chosen, false);
 <input type="file" id="input" />

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM