Google Apps Script: Check upload file exist or emp

2019-09-10 08:38发布

问题:

I try to build condition to check either the file is uploaded before submit. Current situation is, it success to send/submit either file uploaded or not. When I try to get the file use var file = e.parameter.file, it give a string FileUpload. Can anyone help me?

function  setFormUpload() {
  var sheet = SpreadsheetApp.getActiveSpreadsheet();
  var app = UiApp.createApplication().setTitle("Upload File");
  var form = app.createFormPanel().setId('form').setEncoding('multipart/form-data');
  var formContent = app.createVerticalPanel();
  var infoBox = app.createLabel().setVisible(false).setId('infoBox');

  form.add(formContent);  
  formContent.add(app.createFileUpload().setName('file'));
  formContent.add(app.createSubmitButton('Upload'));
  app.add(form);
  sheet.show(app);
}


function doPost(e){
  var app = UiApp.getActiveApplication();
  var file = e.parameter.file;

  if(file == ''){
    var text = 'file empty';
  } else {
    var text = 'file exist';
  }

  app.getElementById('infoBox').setText(text).setVisible(true);
  return app;
}

回答1:

Instead of checking the actual value of e.parameter.file, (as this always return FileUpload whether empty or not) check its length. It will be zero if there is no file.

if(file.length > 0){
    var text = 'file empty';
} else {
    var text = 'file exist';
}


回答2:

Again this doesn't check if folder exists

function checkfileexists(fn){

     var destFolder = DriveApp.getFolderById('...');
     var destFileId = destFolder.getFilesByName(fn);
     return destFileId.hasNext();

}


回答3:

I had a similar problem with docs. Hopefully this helps.

var destFolder = DocsList.getFolder('ScriptTesting');
var destFileId = destFolder.find('Dest1');
if (!destFileId[0]) 
  DocumentApp.getUi().alert('Problem finding Dest File...');

This does not check if the folder exists.