[英]How to validate a file upload field using Javascript/ google App script
All全部
I have been stuck on my simple project for while now.我一直坚持我的简单项目有一段时间了。 I have created a web app code that allows others to upload their pdf file to my google folder but the problem that I could not figure out who to set specific file extension so other do not upload only accepted extension "pdf".我创建了一个 web 应用程序代码,允许其他人将他们的 pdf 文件上传到我的 google 文件夹,但问题是我无法弄清楚谁来设置特定的文件扩展名,所以其他人不上传只接受的扩展名“pdf”。 inside my code, there is a function supposed to prevent any type of extension except for pdf but it did not work.在我的代码中,有一个 function 应该防止除 pdf 之外的任何类型的扩展,但它不起作用。
<form>
<input type="file" name="myFile" accept= "checkfile(sender);" id='file' >
<br>
<br>
<input type="button" id="submitBtn" value="Upload Files">
<label id="resp"></label>
</form>
<script>
document.getElementById('submitBtn').addEventListener('click',
function(e){
google.script.run.withSuccessHandler(onSuccess).uploadFiles(this.parentNode)
})
function onSuccess(data){
document.getElementById('resp').innerHTML = "File Uploaded to the path " +data;
function checkfile(sender) {
var element= document.getElementById('file')
if ( sender !== '.pdf') {
return sender.preventDefault();
} else {
return true;
}
}
}
</script>
code.gs代码.gs
function doGet() {
var html = HtmlService.createHtmlOutputFromFile('form');
return html.setXFrameOptionsMode(HtmlService.XFrameOptionsMode.ALLOWALL);
}
function uploadFiles(data)
{
var file = data.myFile;
var folder = DriveApp.getFolderById('...........');
var createFile = folder.createFile(file);
return createFile.getUrl();
}
accept
in <input>
<input type="file" accept=".pdf"/>
在<input>
<input type="file" accept=".pdf"/>
中使用accept
function uploadFiles(filename, data) {
if (!!filename.match('^.*\.(pdf|PDF)$')) return false; // or throw error
}
Looks like you're trying to match the filename with just ".pdf" - You could try using regex to match to only the end of the file.看起来您正在尝试仅将文件名与“.pdf”匹配 - 您可以尝试使用正则表达式仅匹配文件的末尾。
const regex = "^.+\.pdf$"
if (!sender.match(regex)) {
return sender.preventDefault();
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.