是否可以将按钮设置为文件上传按钮?
2022-08-30 15:02:12
您可以在代码中保留 a,并在用户单击“上传 MB”
按钮时使用 javascript 单击它。<input type='file' hidden/>
看看这个小提琴。
下面是代码段。
document.getElementById('buttonid').addEventListener('click', openDialog);
function openDialog() {
document.getElementById('fileid').click();
}
<input id='fileid' type='file' hidden/>
<input id='buttonid' type='button' value='Upload MB' />
这是完整的代码。
<html>
<head>
<script>
function setup() {
document.getElementById('buttonid').addEventListener('click', openDialog);
function openDialog() {
document.getElementById('fileid').click();
}
document.getElementById('fileid').addEventListener('change', submitForm);
function submitForm() {
document.getElementById('formid').submit();
}
}
</script>
</head>
<body onload="setup()">
<form id='formid' action="form.php" method="POST" enctype="multipart/form-data">
<input id='fileid' type='file' name='filename' hidden/>
<input id='buttonid' type='button' value='Upload MB' />
<input type='submit' value='Submit' />
</form>
</body>
</html>
我对主题的2美分:全部在代码中,无需将任何输入添加到页面中。
function onClickHandler(ev) {
var el = window._protected_reference = document.createElement("INPUT");
el.type = "file";
el.accept = "image/*";
el.multiple = "multiple"; // remove to have a single file selection
// (cancel will not trigger 'change')
el.addEventListener('change', function(ev2) {
// access el.files[] to do something with it (test its length!)
// add first image, if available
if (el.files.length) {
document.getElementById('out').src = URL.createObjectURL(el.files[0]);
}
// test some async handling
new Promise(function(resolve) {
setTimeout(function() { console.log(el.files); resolve(); }, 1000);
})
.then(function() {
// clear / free reference
el = window._protected_reference = undefined;
});
});
el.click(); // open
}
#out {
width: 100px; height: 100px; object-fit: contain; display: block;
}
/* hide if it would show the error img */
#out[src=''] {
opacity: 0;
}
<img src="" id="out" />
<button onClick="onClickHandler(event)">select an IMAGE</button>
注意:在处理所有数据之前,可能会收集垃圾信息 - 添加它将使任何 Promise 处理的引用保持活动状态。el
window.*