javascript - 发布文件是否需要
问题描述
我的 webapp 的标题中有一个选项可以选择带有 的文件<input type='file'/>
,并且我希望在选择文件后立即开始将其上传到我的本地 nodejs 服务器。
我是否需要将其封装在具有 POST 属性的标签中并使用按钮确认?和/或是否可以在选择文件而不是使用按钮时立即调用 POST?
解决方案
<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" />
推荐阅读
- tfs - 如何将主机条目添加到 Microsoft 托管代理 (Azure DevOps)
- ruby-on-rails - 我可以根据没有匹配项创建 Active Record 关系吗
- matlab - 如何在 h=dt 的实际系统中将欧拉方法应用于 ODE 一阶?
- javascript - IE11 中的中止控制器不起作用。任何方式来支持它
- ruby-on-rails - Rails 销毁操作不会删除
- codeception - 如何忽略测试器中的html->单击代码接收?
- python - 更改流程的变量
- javascript - 导出 Highcharts 时无法根据需要禁用图例标题/启用图例标题
- java - ModelMapper 在将实体转换为 DTO 时产生异常
- php - 发送到某些地址时出现 Smtp 问题 - 错误:服务器不接受 rcpt