我在我的 webapp 的标题中有一个选项来选择带有 <input type='file'/>
的文件,我希望在选择文件后立即开始将其上传到我的本地 nodejs 服务器。
是否需要封装在带有POST属性的标签中,并通过按钮确认?和/或者是否可以在选择文件而不是使用按钮时立即调用 POSTing?
最佳答案
您为 <input type="file" id="input">
设置了一个 onchange 事件榆树。
Javascript
let input = document.getElementById('input');
input.onchange = function(e) {
if (file.files.length > 1) {
// Upload
}
};
在选定文件的表单值出现并且我们的 onchange
之后事件被触发。然后我们使用 Fetch post 发布文件。
Example
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" />
关于javascript - 发布文件是否需要 <form> 标签和按钮?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55399846/