首页 > 解决方案 > 发布文件是否需要

标签和按钮?

问题描述

我的 webapp 的标题中有一个选项可以选择带有 的文件<input type='file'/>,并且我希望在选择文件后立即开始将其上传到我的本地 nodejs 服务器。

我是否需要将其封装在具有 POST 属性的标签中并使用按钮确认?和/或是否可以在选择文件而不是使用按钮时立即调用 POST?

标签: javascriptfilepostinputfile-upload

解决方案


<input type="file" id="input">你为榆树设置了一个 onchange 事件。

Javascript

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

在选定文件的表单值出现并onchange触发我们的事件之后。然后,我们使用 Fetch 帖子发布文件。

例子

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" />


推荐阅读