How to Use Advanced Drive Service to Upload Files - google-apps-script

I have the following Google Apps Script that takes a file from an upload form and stores it automatically in my Google Drive (full code in snippet below). The problem is with this section of it:
var file = folder.createFile(blob);
//Get root folder and pull all existing folders, plus setup variables pulled from form
var dropbox = form.Country;
var filename = form.reportType+".xls";
var rootfolder = DriveApp.getFolderById("0Byvtwn42HsoxfnVoSjB2NWprYnRiQ2VWUDZEendNOWwwM1FOZk1EVnJOU3BxQXhwU0pDSE0");
//Note root folder is Live Uploads Folder in Flatworld App folder structure
var folder, folders = rootfolder.getFoldersByName(dropbox);
//Check if folder exists and if not create
if (folders.hasNext()) {
folder = folders.next();
} else {
folder = rootfolder.createFolder(dropbox);
}
//Check if file already exists and delete if it does
var file, files = folder.getFilesByName(filename);
while( files.hasNext()){
file = files.next();
file.setTrashed(true);
}
//Upload file and set various properties
var blob = form.myFile;
var file = folder.createFile(blob);
var timeStamp = new Date();
file.setDescription("Uploaded via BNI Upload Form by " + form.myName + " on: " + timeStamp);
//Set file name slightly differently for Weekly Member Report (do not want to overright based on name just keep each extract so add timestamp to name)
if (form.reportType == "Member Weekly"){
file.setName(form.reportType + timeStamp + ".xls");
}
else
{
file.setName(filename);
}
I'm using the standard Google App Services createFile method of the DriveApp class but this has a small file upload size and is proving very slow to upload larger files close to this limit.
I would like to move to the Advanced Google Services that allow you to use Google's public API methods direct in Google Apps Scripts. I've enabled the Drive API and think I want to use something like this:
function uploadFile() {
var image = UrlFetchApp.fetch('http://goo.gl/nd7zjB').getBlob();
var file = {
title: 'google_logo.png',
mimeType: 'image/png'
};
file = Drive.Files.insert(file, image);
Logger.log('ID: %s, File size (bytes): %s', file.id, file.fileSize);
}
But I'm struggling to implement it alongside my existing code, and the example languages are all for those coding in other languages and using the API rather than just writing in Apps Script.
Please can anyone suggest the code revision required to use the advanced method, allowing a quicker and larger upload?

There is a bit of to'ing and fro'ing possible between Drive and DriveApp rather than getting knee-dep into the pure Drive API.
//Upload file and set various properties
var mediaData = form.myFile;
var timeStamp = new Date();
var resource = {
title: (form.reportType == "Member Weekly") ? form.reportType + timeStamp + ".xls" : filename,
mimetype: 'application/vnd.ms-excel',
description: "Uploaded via BNI Upload Form by " + form.myName + " on: " + timeStamp
};
var file = Drive.Files.insert(resource, mediaData); // create file using Drive API
var fileId = file.id;
var DriveAppFile = DriveApp.getFileById(fileId); // retrieve file in DriveApp scope.
DriveApp.removeFile(DriveAppFile); // remove new file from Users root My Drive
folder.addFile(DriveAppFile); // puts file in selected folder
Drive in this code refers to the Drive API Advanced Google Service that is enabled from the Resources menu. You'll need to enable it as an API from the developer console also. These advanced services attach themselves to your script much like Liraries. Drive here is what the library is defaulting to.
How to enable Advanced Services

Related

unable to copy the gmail file to google sheets. It throws the error as:API call to drive.files.insert failed with error: Invalid mime type provided [duplicate]

This is a continuation from How to Use Advanced Drive Service to Upload Files.
My Webapp consists of an upload form for data files, which are then stored on Google Drive. (Full code in snippet below.)
I'm having a problem with the following line of code:
var file = Drive.Files.insert(resource, mediaData); // create file using Drive API
try {
//Get root folder and pull all existing folders, plus setup variables pulled from form
var dropbox = form.Country;
var timeStamp = new Date();
//Set file name slightly differently for Weekly Member Report (do not want to overright based on name just keep each extract so add timestamp to name)
if (form.reportType == "Member Weekly"){
var filename = form.reportType + timeStamp + ".xls";
}
else
{
var filename = form.reportType+".xls";
}
var rootfolder = DriveApp.getFolderById("0Byvtwn42HsoxfnVoSjB2NWprYnRiQ2VWUDZEendNOWwwM1FOZk1EVnJOU3BxQXhwU0pDSE0");
//Note root folder is Live Uploads Folder in Flatworld App folder structure
var folder, folders = rootfolder.getFoldersByName(dropbox);
//Check if folder exists and if not create
if (folders.hasNext()) {
folder = folders.next();
} else {
folder = rootfolder.createFolder(dropbox);
}
var FolderURL = folder.getUrl(); // Retain URL of folder for final end message to user
//Check if file already exists and delete if it does
var file, files = folder.getFilesByName(filename);
while( files.hasNext()){
file = files.next();
file.setTrashed(true);
}
//New Code from Stackover Flow:
//Upload file and set various properties
var mediaData = form.myFile;
var resource = {
title: filename,
mimetype: 'application/vnd.ms-excel',
description: "Uploaded via BNI Upload Form by " + form.myName + " on: " + timeStamp
};
var file = Drive.Files.insert(resource, mediaData); // create file using Drive API
var fileId = file.id;
var DriveAppFile = DriveApp.getFileById(fileId); // retrieve file in DriveApp scope.
var FileURL = DriveAppFile.getUrl(); //Retain URL of file for final end message to user
DriveApp.removeFile(DriveAppFile); // remove new file from Users root My Drive
folder.addFile(DriveAppFile); // puts file in selected folder
//End of New code from Stackover Flow
//Success message displayed to user
return "Thanks! File uploaded successfully to: <br><br><b>Folder Location:</b> " + FolderURL + "<br>" + "<b>File:</b> " + FileURL + ". <br><br>For any queries please email user#example.com copying the URLs displayed here in your email. You can close this browser window now or use the link below to upload another file.<br><br>";
} catch (error) {
//Catch error return it to user and email with error details
Its throwing the error message "Empty Response" on the line of code above when we try and upload a large file (15MB) Do you have any suggestions. This is well inside the Files insert limit of 5120GB and the code works fine on smaller files.
I've now tried to add in a loop in function to try the upload a couple of times, still throwing the same error sadly:
//setup function that will return null if file is not uploaded correctly
function createDriveFile(resource_f, mediaData_f){
try{
var file = Drive.Files.insert(resource_f, mediaData_f); // create file using Drive API
return file;
} catch (e) {return null;}
}
//try upload and loop if null
var maxTries = 3;
var tries = 0;
do {
tries = tries + 1;
if (tries > 0) {
var file = createDriveFile(resource, mediaData);
Logger.log("I'm trying to upload, try number: " + tries);
}
} while ((file == null) && (tries < maxTries));
if (file == null) {
var file = Drive.Files.insert(resource, mediaData); // try one laste time to create file using Drive API - outside loop function so if error is thrown script stops
}
The error only seems to occur on a larger file, even if we reduce the size of the same file that solves error so do we need to adjust the upload process to account for a larger file. Is there a Google Apps Script equivalent of making the API upload request resumable?
Your file size is the determinant factor here. Referencing the documentation suggests the simple upload method used here is good for up to 5MB only.
https://developers.google.com/drive/web/manage-uploads
Your comments seem to confirm this is what is happening for you.
As you hinted, use the resumable upload method. Use the uploadType: resumable parameter flag – API docs on the insert method describes how.
You can also check the naming of the file, for me I had a slash in the name which is why it would not upload. So take away any special characters before uploading and it should work.

Prevent Google Drive Service API from extracting text when converting images

I've got a script that processes files uploaded to Google Drive and if they are not pdf files it converts them into Google Docs, then converts the Google Doc file to pdf. This all works as required.
The problem I have is if the file to be converted to Google Docs is an image file, the "new" Google Docs file not only contains the image but also text extracted via OCR (I assume). I've tried setting that option to false to no avail.
Please help, all I want is to convert image files to pdf without extracting any text from the images.
function afterUpload(form_upload_items, suid, lname,scans_folder){
var pdf_file_ids, pdf_files, processed_folder, converted_file;
form_upload_items.forEach (function (form_upload_item_id) {
var uploaded_file = DriveApp.getFileById(form_upload_item_id);
const uft = uploaded_file.getMimeType();
Logger.log("item has name of '%s' and is of type '%s'", uploaded_file.
getName(), uft);
processed_folder = scans_folder.getFoldersByName("Processed").next();
var file_description = uploaded_file.getDescription();
if (file_description==null){
file_description=" "
}
if (file_description.includes("Scanned")){
Logger.log("Already scanned '%s'", uploaded_file.getName());
}
else{
uploaded_file.setDescription("Scanned");
file_description = uploaded_file.getDescription();
}
if (file_description.includes("Processed")) {
Logger.log("Already processed %s", uploaded_file.getName());
}
else{
if (uft !=MimeType.PDF && !file_description.includes("Converted")){ // convert file to pdf if required
//Convert to Google docs
const file_blob = uploaded_file.getBlob();
const options ={
ocr: false,
supportsAllDrives: true
}
const res = Drive.Files.insert({ // Drive API of Advanced Google services is used.
"mimeType": "application/vnd.google-apps.document",
"title": uploaded_file.getName() + "_gdocs_conv"
}, file_blob,options);
uploaded_file.moveTo(processed_folder);
uploaded_file.setDescription(file_description+", Converted");
converted_file = DriveApp.getFileById(res.id);
converted_file.moveTo(processed_folder);
const blobPDF = converted_file.getAs(MimeType.PDF);
//finally convert google docs to PDF
uploaded_file = scans_folder.createFile(blobPDF);
Logger.log("Converted %s to pdf",uploaded_file.getName());
}
}
});
const query = "title contains '" +suid+"'"
const scanned_files = scans_folder.searchFiles(query);
pdf_file_ids = [];
pdf_files = [];
while (scanned_files.hasNext()){
const scanned_file = scanned_files.next();
Logger.log("%s %s",scanned_file.getName(), scanned_file.getDescription());
pdf_file_ids.push(scanned_file.getId());
pdf_files.push(scanned_file);
}
var function_result = {};
var documents_folder = scans_folder.getParents().next();
function_result["file_name_prefix"] = suid+" "+lname;
function_result["pdf_files"] = pdf_file_ids;
function_result["documents_folder_id"] = documents_folder.getId();
}
The problem is that you are converting image files into a Google Document, instead of creating a file type that could be converted into a PDF by Google Drive. To do this, insert the image to this newly created file then convert the resulting document into a PDF. Depending on the result that you requires you might create an HTML file, Google Document or a Google Slides (Google Drawings might be the best but there isn't a Google Apps Script service for that).
The "easier" solution is to create an HTML file. Here is a sample adapted from Tanaike's answer to Show images inside a pdf created with Gloogle Apps Script Blob
function myFunction() {
// image
var url = "https://cdn.sstatic.net/Sites/stackoverflow/company/img/logos/so/so-icon.png?v=c78bd457575a";
var blob = UrlFetchApp.fetch(url).getBlob();
var b64 = blob.getContentType() + ';base64,'+ Utilities.base64Encode(blob.getBytes());
var html =`<img src="data:${ b64 }">`;
var h = HtmlService.createHtmlOutput(html);
// Create from HTML to PDF file.
DriveApp.createFile(h.getAs("application/pdf").setName("text.pdf"));
}
Related
getBlob() causing "Invalid image data." Error. Google Apps Script

Moving Files In Google Drive Using Google Script

I'm trying to create documents using information posted through Google forms, then once the document is created I would like to move the document into a shared folder for people to view.
At the moment I have the script taking all of the information from the Google Forms linked spreadsheet.
Using that information I'm using the following code to create the document:
var targetFolder = DriveApp.getFolderById(TARGET_FOLDER_ID);
var newDoc = DocumentApp.create(requestID + " - " + requestSummary);
This is creating the document successfully in my Google Drive root folder, but I can't seem to move it where I want to move it to.
I've seen a lot of posts suggesting use stuff like targetFolder.addFile(newDoc) but that doesn't work, similarly I've seen examples like newDoc.addToFolder(targetFolder) but again this isn't working for me.
It seems that all the online questions people have already asked about this are using the previous API versions that are no longer applicable and these methods do not apply to the new DriveApp functionality.
What I would like, if possible, is to create the new document as above so that I can edit the contents using the script, then be able to move that file to a shared folder. (From what I understand there is no 'move' function at present, so making a copy and deleting the old one will suffice).
If we make a copy of the file and trash the original, it would change the file URL and also the file sharing settings won't be preserved.
In Drive, it is possible to add a file to multiple folders with the .addFolder() method of DriveApp service. You can add the file to the target folder and then remove the file from the immediate parent folder.
function moveFiles(sourceFileId, targetFolderId) {
var file = DriveApp.getFileById(sourceFileId);
var folder = DriveApp.getFolderById(targetFolderId);
file.moveTo(folder);
}
This is my first post! I know this has been answered a few times, but I actually came across this question while working on my project, and while reviewing the Apps Script documentation, I figured out a concise way to do it. A variation of some1's answer.
var file = DriveApp.getFileById(fileid);
DriveApp.getFolderById(folderid).addFile(file);
DriveApp.getRootFolder().removeFile(file);
Hope it helps!
There is no direct method in the File or Folder Classes to move files from one folder in Google Drive to another. As you mentioned you can copy the file to another folder with the method makeCopy() and then delete it with setTrashed(), the code should look like this:
var targetFolder = DriveApp.getFolderById(TARGET_FOLDER_ID);
var newDoc = DocumentApp.create(requestID + " - " + requestSummary); // Creates the Document in the user's Drive root folder
// Modify the new document here, example:
// var body = newDoc.getBody();
// body.appendParagraph("A paragraph.");
// newDoc.saveAndClose();
var driveFile = DriveApp.getFileById(newDoc.getId()); // Gets the drive File
driveFile.makeCopy(newDoc.getName(), targetFolder); // Create a copy of the newDoc in the shared folder
driveFile.setTrashed(true); // sets the file in the trash of the user's Drive
EDIT:
In a second thought and taking into account Ruben's comments. I agree that it is a better practice to implement Amit's answer.
It looks like there is now a moveTo() function with the Drive API (advanced services) that makes it easy to move files:
moveTo(destination)
Moves this item to the provided destination folder.
The current user must be the owner of the file or have at least edit
access to the item's current parent folder in order to move the item
to the destination folder.
Here is some code I used to move all files from the "screenshot input" folder to the "screenshot processed" folder:
var inputFolder = DriveApp.getFolderById(SCREENSHOT_INPUT_FOLDER_ID);
var processedFolder = DriveApp.getFolderById(SCREENSHOT_PROCESSED_FOLDER_ID);
var files = inputFolder.getFiles();
while (files.hasNext()) {
var file = files.next();
file.moveTo(processedFolder);
}
A bit safer approach compared to the previous ones:
If you remove link to the file first, then you will not be able to addFile.
If file is already located in the target folder, then the approach provided by Amit (https://stackoverflow.com/a/38810986/11912486) only removes file.
So, I suggest to use the following approach:
function move_file(file_id, target_folder_id) {
var source_file = DriveApp.getFileById(file_id);
var source_folder = source_file.getParents().next();
if (source_folder.getId() != target_folder_id) {
DriveApp.getFolderById(target_folder_id).addFile(source_file);
source_folder.removeFile(source_file);
}
}
can be improved by:
javascript camel style
multiple locations validation
Use File.moveTo(destination).
var newFileId = newDoc.getId();
var newFile = DriveApp.getFileById(newFileId);
newFile.moveTo(targetFolder);
Try this:
var file = DriveApp.getFileById(newDoc.getId());
targetFolder.addFile(file);
//DriveApp.getFolderById('root').removeFile(file); // remove from root
This question has been answered, but here is a slightly different configuration:
function moveFile(parameterObject) {
var currentFolderID,file,fileToMoveID,sourceFolder,targetFolder,targetFolderID;
fileToMoveID = parameterObject.fileToMoveID;
currentFolderID = parameterObject.currentFolderID;
targetFolderID = parameterObject.targetFolderID;
file = DriveApp.getFileById(fileToMoveID);//Get the file to move
if (!file) {
functionToHandleThisKindOfThing("there is no file");
return;
}
if (currentFolderID) {//The folder ID holding the current file was passed in
sourceFolder = DriveApp.getFolderById(currentFolderID);
} else {//No ID for the current folder
sourceFolder = file.getParents();
if (sourceFolder) {
if (sourceFolder.hasNext()) {
sourceFolder = sourceFolder.next();
}
}
}
targetFolder = DriveApp.getFolderById(targetFolderID);
targetFolder.addFile(file);
sourceFolder.removeFile(file);
}
function testCode() {
var o;
o = {
'fileToMoveID':"File ID of file to Move",
"targetFolderID":"ID of folder to Move to"
}
moveFile(o);
}
The script transfers all your personal files to a shared disk (Team drive). Saves the folder structure.
DRIVE_FOLDER_ID = '111aaa'; // Folder ID on the shared drive
function start() {
var files = DriveApp.searchFiles('"me" in owners');
while (files.hasNext()) {
var file = files.next();
newPath = fileMoveWithPath(file, DRIVE_FOLDER_ID);
console.info("New path: ", getFullPath(newPath));
}
}
function fileMoveWithPath(file, root) {
var folders = [],
parent = file.getParents();
// Проходим по иерархии папок текущего файла до корня
while (parent.hasNext()) {
parent = parent.next();
folders.push(parent);
parent = parent.getParents();
}
console.info("Old path: ", getFullPath(file));
if (folders.length > 0)
targetPath = makeNewPath(folders, DriveApp.getFolderById(root));
else
targetPath = DriveApp.getFolderById(root);
if (targetPath) {
targetFile = file.moveTo(targetPath);
return targetFile;
};
return;
}
function makeNewPath(folders, newroot) {
var f = folders.pop();
var query = "'" + newroot.getId() + "' in parents and title = '" + f.getName() + "' and mimeType='application/vnd.google-apps.folder' "
var targetFolder = DriveApp.searchFolders(query);
if (targetFolder.hasNext())
targetFolder = targetFolder.next()
else
targetFolder = newroot.createFolder(f.getName());
if (folders.length > 0)
return makeNewPath(folders, targetFolder)
else
return targetFolder;
}
function getFullPath(file) {
var folders = [],
parent = file.getParents();
while (parent.hasNext()) {
parent = parent.next();
folders.push(parent.getName());
parent = parent.getParents();
}
if (folders.length) {
return '> /' + folders.reverse().join("/") + '/' + file.getName();
}
return '> /' + file.getName();
}

Create a Google Doc file directly in a Google Drive folder

How do I create a Google document in a Google Drive folder?
I know that I can create a file in a folder like this.
var folder = DriveApp.createFolder("A Folder")
folder.createFile("filename.file", "Some text")
But how I can create a document in a folder using Google Apps Script.
The other answer is correct but the file will exist in your folder AND in your "drive" folder (the root folder).
To avoid that, simply remove it from there !
code :
var doc = DocumentApp.create('Document Name'),
docFile = DriveApp.getFileById( doc.getId() );
DriveApp.getFolderById('0B3°°°°°°°1lXWkk').addFile( docFile );
DriveApp.getRootFolder().removeFile(docFile);
With document it's a bit different, you first create it then move to the folder:
var doc = DocumentApp.create('Document Name'),
docFile = DriveApp.getFileById( doc.getId() );
DriveApp.getFolderById(foldId).addFile( docFile );
This is how to create a new Google Doc in a specific folder. When the Doc is created, the mime type must be set.
Note that this code does NOT first create a Doc file, move it, and then delete the file in the Root Drive. This code creates a new Google Doc type file directly in a folder.
You will need to use the Advanced Drive API. It must be enabled in two places.
From the code editor choose "Resources" and then choose, "Advanced Google services"
Click the button for "Drive API" so that it is ON.
Click the link: Google Cloud Platform API Dashboard.
Search Drive API
Choose Google Drive API from search list
Enable the Drive API
Code:
function myFunction(e) {
var doc,fileResource,folder,ID_of_newFile,multipleFolders,newFile,
newDocName,rng,sh,ss,ssFile,ssID;
var name = e.values[1];
var kantoor = e.values[2];
newDocName = 'Sleuteloverdracht ' + name;//Set the name of the new file
rng = e.range;//Get range in the spreadsheet that received the data
sh = rng.getSheet();//Get sheet tab
ss = sh.getParent();//Get spreadsheet
ssID = ss.getSheetId();//Get file ID of spreadsheet - Integer
ssFile = DriveApp.getFileById(ssID);//Get the spreadsheet file in order to get the
//folder to put the new file in
multipleFolders = ssFile.getParents();//Get all parent folders of the spreadsheet file
folder = multipleFolders.next();//Get the folder of the spreadsheet
fileResource = {
'title': newDocName,
"parents": [{'id':folder.getId()}], //<--By setting this parent ID to the
//folder's ID, it creates this file in the correct folder
'mimeType': 'application/vnd.google-apps.document'
};
newFile = Drive.Files.insert(fileResource);//Create the new document file
// directly into the same folder as the spreadsheet
ID_of_newFile = newFile.getId();
//Logger.log(ID_of_newFile)
doc = DocumentApp.openById(newFile.getId());//Open the new file as a Google document
var body = doc.getBody();
body.appendParagraph('Sleuteloverdracht ' + name);
body.appendParagraph('Uw naam is '+ name + '\n' +
'U heeft de sleutel van kantoor '+ kantoor);
doc.saveAndClose();
}
Serge insas's answer helped me, but the methods are now deprecated in 2021. Here is what worked for me.
var folder = 'Your Folder Id'
var title = 'Your File Name'
var doc = DocumentApp.create(title);
docFile = DriveApp.getFileById(doc.getId());
docFile.moveTo(folder);
To add to #Kriggs answer.
To remove from the root folder:
DriveApp.getRootFolder().removeFile(file)
Otherwise, it will be in the root level and the new location.
var folder = DriveApp.createFolder ("A Folder");
var file = DriveApp.createFile ("filename.file", "Some text");
file.moveTo (folder);
You can also use the Drive App to create a copy of a Google document (e.g. a template)
use this:
DriveApp.getFileById(templateFileId).makeCopy(name, destination);

Advanced Drive Service returning Empty Response Error when inserting file

This is a continuation from How to Use Advanced Drive Service to Upload Files.
My Webapp consists of an upload form for data files, which are then stored on Google Drive. (Full code in snippet below.)
I'm having a problem with the following line of code:
var file = Drive.Files.insert(resource, mediaData); // create file using Drive API
try {
//Get root folder and pull all existing folders, plus setup variables pulled from form
var dropbox = form.Country;
var timeStamp = new Date();
//Set file name slightly differently for Weekly Member Report (do not want to overright based on name just keep each extract so add timestamp to name)
if (form.reportType == "Member Weekly"){
var filename = form.reportType + timeStamp + ".xls";
}
else
{
var filename = form.reportType+".xls";
}
var rootfolder = DriveApp.getFolderById("0Byvtwn42HsoxfnVoSjB2NWprYnRiQ2VWUDZEendNOWwwM1FOZk1EVnJOU3BxQXhwU0pDSE0");
//Note root folder is Live Uploads Folder in Flatworld App folder structure
var folder, folders = rootfolder.getFoldersByName(dropbox);
//Check if folder exists and if not create
if (folders.hasNext()) {
folder = folders.next();
} else {
folder = rootfolder.createFolder(dropbox);
}
var FolderURL = folder.getUrl(); // Retain URL of folder for final end message to user
//Check if file already exists and delete if it does
var file, files = folder.getFilesByName(filename);
while( files.hasNext()){
file = files.next();
file.setTrashed(true);
}
//New Code from Stackover Flow:
//Upload file and set various properties
var mediaData = form.myFile;
var resource = {
title: filename,
mimetype: 'application/vnd.ms-excel',
description: "Uploaded via BNI Upload Form by " + form.myName + " on: " + timeStamp
};
var file = Drive.Files.insert(resource, mediaData); // create file using Drive API
var fileId = file.id;
var DriveAppFile = DriveApp.getFileById(fileId); // retrieve file in DriveApp scope.
var FileURL = DriveAppFile.getUrl(); //Retain URL of file for final end message to user
DriveApp.removeFile(DriveAppFile); // remove new file from Users root My Drive
folder.addFile(DriveAppFile); // puts file in selected folder
//End of New code from Stackover Flow
//Success message displayed to user
return "Thanks! File uploaded successfully to: <br><br><b>Folder Location:</b> " + FolderURL + "<br>" + "<b>File:</b> " + FileURL + ". <br><br>For any queries please email user#example.com copying the URLs displayed here in your email. You can close this browser window now or use the link below to upload another file.<br><br>";
} catch (error) {
//Catch error return it to user and email with error details
Its throwing the error message "Empty Response" on the line of code above when we try and upload a large file (15MB) Do you have any suggestions. This is well inside the Files insert limit of 5120GB and the code works fine on smaller files.
I've now tried to add in a loop in function to try the upload a couple of times, still throwing the same error sadly:
//setup function that will return null if file is not uploaded correctly
function createDriveFile(resource_f, mediaData_f){
try{
var file = Drive.Files.insert(resource_f, mediaData_f); // create file using Drive API
return file;
} catch (e) {return null;}
}
//try upload and loop if null
var maxTries = 3;
var tries = 0;
do {
tries = tries + 1;
if (tries > 0) {
var file = createDriveFile(resource, mediaData);
Logger.log("I'm trying to upload, try number: " + tries);
}
} while ((file == null) && (tries < maxTries));
if (file == null) {
var file = Drive.Files.insert(resource, mediaData); // try one laste time to create file using Drive API - outside loop function so if error is thrown script stops
}
The error only seems to occur on a larger file, even if we reduce the size of the same file that solves error so do we need to adjust the upload process to account for a larger file. Is there a Google Apps Script equivalent of making the API upload request resumable?
Your file size is the determinant factor here. Referencing the documentation suggests the simple upload method used here is good for up to 5MB only.
https://developers.google.com/drive/web/manage-uploads
Your comments seem to confirm this is what is happening for you.
As you hinted, use the resumable upload method. Use the uploadType: resumable parameter flag – API docs on the insert method describes how.
You can also check the naming of the file, for me I had a slash in the name which is why it would not upload. So take away any special characters before uploading and it should work.