Я пытаюсь создать пользовательскую веб-форму, где люди могли бы загружать свое резюме и лицензию на мой Google Диск.В сети я нашел некоторый код, который я немного изменил, и он вроде работает.
code.gs
var emailTo= "test@test.com"
function doPost(e) {
try {
var data = e.parameter.fileContent; // First attachment
var filename = e.parameter.filename; // First attachment filename
var data2 = e.parameter.fileContent2; // Second attachment
var filename2 = e.parameter.filename2; // Second attachment filename
var email = e.parameter.Email;
var name = e.parameter.Name;
var result=uploadFileToGoogleDrive(data,filename,data2,filename2,name,email,e);
return ContentService // return json success results
.createTextOutput(
JSON.stringify({"result":"success",
"data": JSON.stringify(result) }))
.setMimeType(ContentService.MimeType.JSON);
} catch(error) { // if error return this
Logger.log(error);
return ContentService
.createTextOutput(JSON.stringify({"result":"error", "error": error}))
.setMimeType(ContentService.MimeType.JSON);
}
}
function doGet() {
return HtmlService.createHtmlOutputFromFile('Form').setSandboxMode(
HtmlService.SandboxMode.IFRAME);
}
// new property service GLOBAL
var SCRIPT_PROP = PropertiesService.getScriptProperties();
// see: https://developers.google.com/apps-script/reference/properties/
/**
* select the sheet
*/
function setup() {
var doc = SpreadsheetApp.getActiveSpreadsheet();
SCRIPT_PROP.setProperty("key", doc.getId());
}
/**
* record_data inserts the data received from the html form submission
* e is the data received from the POST
*/
function record_data(e,fileUrl,fileUrl2) {
try {
var doc = SpreadsheetApp.openById("Spreadsheet ID");
var sheet = doc.getSheetByName('Responses'); // select the responses sheet
var headers = sheet.getRange(1, 1, 1, sheet.getLastColumn()).getValues()[0];
var nextRow = sheet.getLastRow()+1; // get next row
var row = [ new Date() ]; // first element in the row should always be a timestamp
// loop through the header columns
for (var i = 1; i < headers.length; i++) { // start at 1 to avoid Timestamp column
if(headers[i].length > 0 && headers[i] == "Resume") {
row.push(fileUrl); // add data to row
}
else if(headers[i].length > 0 && headers[i] == "License") {
row.push(fileUrl2); // add data to row
}
else if(headers[i].length > 0) {
row.push(e.parameter[headers[i]]); // add data to row
}
}
// more efficient to set values as [][] array than individually
sheet.getRange(nextRow, 1, 1, row.length).setValues([row]);
}
catch(error) {
Logger.log(e);
}
finally {
return;
}
}
function uploadFileToGoogleDrive(data, file, data2, file2, name, email,e) {
try {
var dropbox = "Application Test";
var folder, folders = DriveApp.getFoldersByName(dropbox);
if (folders.hasNext()) {
folder = folders.next();
} else {
folder = DriveApp.createFolder(dropbox);
}
var contentType = data.substring(5,data.indexOf(';')),
bytes = Utilities.base64Decode(data.substr(data.indexOf('base64,')+7)),
blob = Utilities.newBlob(bytes, contentType, file);
var subfolder = folder.createFolder([name, email].join("-"));
var file = subfolder.createFile(blob);
var fileUrl=file.getUrl();
var contentType2 = data2.substring(5,data2.indexOf(';')),
bytes2 = Utilities.base64Decode(data2.substr(data2.indexOf('base64,')+7)),
blob2 = Utilities.newBlob(bytes2, contentType2, file2);
var file2 = subfolder.createFile(blob2);
var fileUrl2=file2.getUrl();
//Generating Email Body
var html =
'<body>' +
'<h2> New Application </h2>' +
'<p>Name : '+e.parameters.Name+'</p>' +
'<p>Email : '+e.parameters.Email+'</p>' +
'<p>Phone Number : '+e.parameters.Phone+'</p>' +
'<p>Address : '+e.parameters.Address+'</p>' +
'<p>Postal Code : '+e.parameters.Postal+'</p>' +
'<p>File Name : '+e.parameters.filename+'</p>' +
'<p><a href='+file.getUrl()+'>Resume Link</a></p><br />' +
'<p>File Name : '+e.parameters.filename2+'</p>' +
'<p><a href='+file2.getUrl()+'>License</a></p><br />' +
'</body>';
record_data(e,fileUrl,fileUrl2);
MailApp.sendEmail(emailTo, "New Application Recieved","New Application Request Recieved",{htmlBody:html});
return file.getUrl() + file2.getUrl();
} catch (f) {
return ContentService // return json success results
.createTextOutput(
JSON.stringify({"result":"file upload failed",
"data": JSON.stringify(f) }))
.setMimeType(ContentService.MimeType.JSON);
}
}
Form.html
<!DOCTYPE html>
<html>
<head>
<base target="_top">
</head>
<body>
<form id="uploadForm" action="Insert Web App URL" method="POST">
<input type="hidden" value="" name="fileContent" id="fileContent">
<input type="hidden" value="" name="filename" id="filename">
<input type="hidden" value="" name="fileContent2" id="fileContent2">
<input type="hidden" value="" name="filename2" id="filename2">
<label> Name : </label><input required type="text" value="" name="Name" id="Name"><br><br>
<label> Email : </label> <input required type="text" value="" name="Email" id="Email"><br><br>
<label> Phone Number : </label><input required type="text" value="" name="Phone" id="Phone"><br><br>
<label> Address : </label> <input required type="text" value="" name="Address" id="Address"><br><br>
<label> Postal Code : </label><input type="text" value="" name="Postal" id="Postal"><br><br>
</form>
<label> Resume: <input id="Resume" name="Resume" type="file"/>
<label> License: <input id="License" name="License" type="file"/><br><br>
<input value="Submit" type="button" onclick="UploadFile();" />
<script>
function UploadFile() {
var reader = new FileReader();
var file = document.getElementById('Resume').files[0];
var reader2 = new FileReader();
var file2 = document.getElementById('License').files[0];
reader.onload = function(){
document.getElementById('fileContent').value=reader.result;
document.getElementById('filename').value=file.name;
//document.getElementById('uploadForm').submit();
}
reader2.onload = function(){
document.getElementById('fileContent2').value=reader2.result;
document.getElementById('filename2').value=file2.name;
document.getElementById('uploadForm').submit();
}
reader.readAsDataURL(file);
reader2.readAsDataURL(file2);
}
</script>
</body>
</html>
Обычно он загружает только один из файлов (лицензию) и отображает пустой файл без названия для другого, хотя каждые несколько попыток загружает оба файла правильно.