在我的网络应用程序中,我有这段 html。在我的 Mac 上,我假设在任何 PC 上,当我单击它时,我会看到一个窗口,我可以在其中选择文件,并且仅启用 .PDF;但是,当我在 Android 上尝试相同的页面时,我可以选择文件或相机,无论我选择什么,我总是可以选择任何类型的文件。
有没有办法让这个功能也能在 Android 上运行?
<input class="form-control" name="document_upload" type="file"
accept=".pdf" required id="document_upload">
根据 caniuse,这是 Android 版 Chrome 中的预期行为: https://caniuse.com/input-file-accept
根据格式类型提供适当的文件位置/输入,但不会阻止选择其他文件。
您可以添加这个简单的验证,以确保用户通过 JavaScript 选择正确的文件类型:
<input class="form-control" name="document_upload" type="file" accept=".pdf" required id="document_upload">
<script>
document.getElementById('document_upload').addEventListener('change', function() {
const fileInput = this;
const selectedFile = fileInput.files[0];
if (selectedFile) {
if (selectedFile.type === 'application/pdf') {
// Valid file
} else {
// Invalid file
alert('Please, select a PDF file.');
fileInput.value = '';
}
}
});
</script>