1

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". inside my code, there is a function supposed to prevent any type of extension except for pdf but it did not work.

    <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

 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();
}
1
  • in my function uploadFiles(data) I noticed that I cannot open PDF when v8 chrome is enabled it looks the file is corrupted but when I disabled the v8 chrome it is working fine. Why is that happing? How to fix it? Commented Aug 11, 2020 at 22:45

2 Answers 2

3
  1. Use accept in <input> <input type="file" accept=".pdf"/>
  2. Add server side validation for extension
function uploadFiles(filename, data) {
  if (!!filename.match('^.*\.(pdf|PDF)$')) return false; // or throw error
}
Sign up to request clarification or add additional context in comments.

1 Comment

this is not working with the script when I added it to upload files function, I created an error message with function onFailure(data){ document.getElementById('err').innerHTML = ' file is not pdf'; } by using withFailureHandler(onFailure) and it looks script does not read the pdf as a pdf extension
1

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.

const regex = "^.+\.pdf$"
if (!sender.match(regex)) {
    return sender.preventDefault();
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.