Api call to drive files insert failed with error file not found

I am trying to upload a file into one of my company's Google Drive folders but I haven't managed to achieve this without client intervention. So, whenever I use this: package sample; import com.g...

I am trying to upload a file into one of my company’s Google Drive folders but I haven’t managed to achieve this without client intervention. So, whenever I use this:

package sample;

import com.google.api.client.googleapis.auth.oauth2.GoogleAuthorizationCodeFlow;
import com.google.api.client.googleapis.auth.oauth2.GoogleCredential;
import com.google.api.client.googleapis.auth.oauth2.GoogleTokenResponse;
import com.google.api.client.http.FileContent;
import com.google.api.client.http.HttpTransport;
import com.google.api.client.http.javanet.NetHttpTransport;
import com.google.api.client.json.JsonFactory;
import com.google.api.client.json.jackson2.JacksonFactory;
import com.google.api.services.drive.Drive;
import com.google.api.services.drive.DriveScopes;
import com.google.api.services.drive.model.File;
import com.google.api.services.drive.model.ParentReference;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Arrays;

public class DriveCommandLine_srive
{

    private static String CLIENT_ID = "myClientID.apps.googleusercontent.com";
    private static String CLIENT_SECRET = "myClientSecret";

    private static String REDIRECT_URI = "mything";

    public static void main( String[] args ) throws IOException
    {
        HttpTransport httpTransport = new NetHttpTransport( );
        JsonFactory jsonFactory = new JacksonFactory( );

        GoogleAuthorizationCodeFlow flow = new GoogleAuthorizationCodeFlow.Builder( httpTransport, jsonFactory, CLIENT_ID, CLIENT_SECRET, Arrays.asList( DriveScopes.DRIVE ) ).setAccessType( "online" ).setApprovalPrompt( "auto" ).build( );

        System.out.println("xxxxx : "  + DriveScopes.DRIVE);

        String url = flow.newAuthorizationUrl( ).setRedirectUri( REDIRECT_URI ).build( );
        System.out.println( "Please open the following URL in your browser then type the authorization code:" );
        System.out.println( "  " + url );
        BufferedReader br = new BufferedReader( new InputStreamReader( System.in ) );
        String code = br.readLine( );

        GoogleTokenResponse response = flow.newTokenRequest( code ).setRedirectUri( REDIRECT_URI ).execute( );
        GoogleCredential credential = new GoogleCredential( ).setFromTokenResponse( response );

        // Create a new authorized API client
        Drive service = new Drive.Builder( httpTransport, jsonFactory, credential ).build( );

        insertFile(service, "Test File Drive", "This is a test file","myCompanysFolderID" , "text/plain", "./data/document.txt");

      }

    /**
     * Insert new file.
     *
     * @param service Drive API service instance.
     * @param title Title of the file to insert, including the extension.
     * @param description Description of the file to insert.
     * @param parentId Optional parent folder's ID.
     * @param mimeType MIME type of the file to insert.
     * @param filename Filename of the file to insert.
     * @return Inserted file metadata if successful, {@code null} otherwise.
     */
    private static File insertFile(Drive service, String title, String description,
        String parentId, String mimeType, String filename) {
      // File's metadata.
      File body = new File();
      body.setTitle(title);
      body.setDescription(description);
      body.setMimeType(mimeType);

      // Set the parent folder.
      if (parentId != null && parentId.length() > 0) {
        body.setParents(
            Arrays.asList(new ParentReference().setId(parentId)));
      }

      // File's content.
      java.io.File fileContent = new java.io.File(filename);
      FileContent mediaContent = new FileContent(mimeType, fileContent);
      try {
        File file = service.files().insert(body, mediaContent).execute();

        // Uncomment the following line to print the File ID.
        System.out.println("File ID: " + file.getId());

        return file;
      } catch (IOException e) {
        System.out.println("An error occured: " + e);
        return null;
      }
    }

}

I manage to successfully upload the file to the company’s folder, but I have to authorize it manually and paste the code each time. So, as I want to make this in an automatic way, I changed the authorization «method» to one that uses a service account p12 key to authorize the client. This is the new code after the change:

package sample;

import com.google.api.client.googleapis.auth.oauth2.GoogleCredential;
import com.google.api.client.googleapis.auth.oauth2.GoogleTokenResponse;
import com.google.api.client.googleapis.javanet.GoogleNetHttpTransport;
import com.google.api.client.http.FileContent;
import com.google.api.client.http.HttpTransport;
import com.google.api.client.http.javanet.NetHttpTransport;
import com.google.api.client.json.JsonFactory;
import com.google.api.client.json.jackson2.JacksonFactory;
import com.google.api.client.util.store.FileDataStoreFactory;
import com.google.api.services.drive.Drive;
import com.google.api.services.drive.DriveScopes;
import com.google.api.services.drive.model.File;
import com.google.api.services.drive.model.ParentReference;


import java.io.IOException;
import java.io.InputStream;
import java.util.Arrays;
import java.util.List;

public class DriveCommandLine2
{

    private static final String KEY_FILE_LOCATION = "data/myp12Key.p12";
    **//Note: this is the mail from a service account in my dev console, it is different from the OAuth client I use in the previous method.**
    private static final String SERVICE_ACCOUNT_EMAIL ="myServiceAccountEmail@appspot.gserviceaccount.com";

    /** Application name. */
    private static final String APPLICATION_NAME =
        "Drive API Java Quickstart";

    /** Global instance of the JSON factory. */
    private static final JsonFactory JSON_FACTORY =
        JacksonFactory.getDefaultInstance();

    public static void main( String[] args ) throws Exception
    {
        //Drive service = getServiceManual();
        Drive service = initializeDrive();
        //insertFile(service, "Test File Drive", "This is a test file","myCompanyFolderID" , "text/plain", "./data/document.txt");
        insertFile(service, "Test File Drive", "This is a test file","" , "text/plain", "./data/document.txt");
      }

    /**
     * Insert new file.
     *
     * @param service Drive API service instance.
     * @param title Title of the file to insert, including the extension.
     * @param description Description of the file to insert.
     * @param parentId Optional parent folder's ID.
     * @param mimeType MIME type of the file to insert.
     * @param filename Filename of the file to insert.
     * @return Inserted file metadata if successful, {@code null} otherwise.
     */
    private static File insertFile(Drive service, String title, String description,
        String parentId, String mimeType, String filename) {
      // File's metadata.
      File body = new File();
      body.setTitle(title);
      body.setDescription(description);
      body.setMimeType(mimeType);

      // Set the parent folder.
      if (parentId != null && parentId.length() > 0) {
        body.setParents(
            Arrays.asList(new ParentReference().setId(parentId)));
      }

      // File's content.
      java.io.File fileContent = new java.io.File(filename);
      FileContent mediaContent = new FileContent(mimeType, fileContent);
      try {
        File file = service.files().insert(body, mediaContent).execute();

        // Uncomment the following line to print the File ID.
        System.out.println("File ID: " + file.getId());

        return file;
      } catch (IOException e) {
        System.out.println("An error occured: " + e);
        return null;
      }
    }


    /////////////////////
    ///NEW GOOGLE ANALYTICS AUTH

    public static java.io.File convIs2File(InputStream inputStream, java.io.File file)
    {
        java.io.OutputStream outputStream = null;

        try {
            // write the inputStream to a FileOutputStream
            outputStream = new java.io.FileOutputStream(file);

            int read = 0;
            byte[] bytes = new byte[1024];

            while ((read = inputStream.read(bytes)) != -1) {
                outputStream.write(bytes, 0, read);
            }

            System.out.println("Done!");

        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (inputStream != null) {
                try {
                    inputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (outputStream != null) {
                try {
                    // outputStream.flush();
                    outputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }

            }
        }
        return file;
    }
    private static Drive initializeDrive() throws Exception {
        // Initializes an authorized analytics service object.

        // Construct a GoogleCredential object with the service account email
        // and p12 file downloaded from the developer console.
        HttpTransport httpTransport = GoogleNetHttpTransport.newTrustedTransport();
        InputStream is = DriveCommandLine2.class.getClassLoader().getResourceAsStream(KEY_FILE_LOCATION);
        java.io.File f = java.io.File.createTempFile("myP12Key", ".p12");
        java.io.File f_used = convIs2File(is,f);
        GoogleCredential credential = new GoogleCredential.Builder()
                .setTransport(httpTransport)
                .setJsonFactory(JSON_FACTORY)
                .setServiceAccountId(SERVICE_ACCOUNT_EMAIL)
                .setServiceAccountPrivateKeyFromP12File(f_used)
                .setServiceAccountScopes(DriveScopes.all())
                .build();

        // Construct the Analytics service object.
        return new Drive.Builder(httpTransport, JSON_FACTORY, credential)
                .setApplicationName(APPLICATION_NAME).build();
    }


}

But when I run this code, I get the following error:

An error occured: com.google.api.client.googleapis.json.GoogleJsonResponseException: 404 Not Found
{
  "code" : 404,
  "errors" : [ {
    "domain" : "global",
    "location" : "file",
    "locationType" : "other",
    "message" : "File not found: myCompanyFolderID",
    "reason" : "notFound"
  } ],
  "message" : "File not found: myCompanyFolderID"
}

So, my guess is that in the previous authorization way, I am using my Client_ID and Client_Secrets to authorize my app to insert things into my company’s Drive space, so I find myCompanyFolder and I am able to insert the file successfully, however, in the second method, I am trying to insert the file into the service account Drive space that I am not able to access (I know this because when I try to insert it in Drive’s root, it works perfectly, however, I am not able to see the file in my root).

So at the end, my question is, is there a way to insert the file into my company’s drive folder without doing the manual authorization? That is, how do I authorize my app to upload the file in my company’s drive without human interaction?

I think the client_secrets way won’t work as I tried it before and it asks me to do it manually the first time I run the code. As I am running my code from a JAR file in a Linux server, this is not practical at all and doesn’t work for me.

Thanks!

scriptPilot

Bug summary

After the script stopped automatically, I resumed manually.
The first file is skipped on resuming, resulting in a missed file.

Please check the file names in the following screenshot.

Bildschirmfoto 2023-02-04 um 12 44 41

Any specific steps to reproduce the issue?

See above.

Oath of good faith

  • I, the author of this Issue, do solemnly swear that I’ve looked real hard for duplicate issues and I came up empty!!

jet082

So I think this might be related to #107, but I wonder if I’m just being dumb and the feature already exists?

So if we have Directory A on Google Drive 1 and Directory A on Google Drive 2 with a backup a year ago — is there a way to only copy the new files in Directory A on Google Drive 1 to Google Drive 2?

Issue #107 requested an automatic process, and I realize why this is impossible — but is it possible to do this manually?

  • I, the author of this Issue, do solemnly swear that I’ve looked real hard for duplicate issues and I came up empty!!

jet082

Bug summary

I kept an eye on the script in question for quite some time to pause it when it began to error out due to #82. However, when I clicked «pause» it claimed to pause, but the spreadsheet kept updating!

Troubled, I removed permissions for gdrive-copy, but it was still running and updating the spreadsheet with errors!

So then I deleted the spreadsheet and other file, waited a bit for it to hopefully crash, then restored the spreadsheet — and it began updating it again

I tried resuming manually and then pausing again. This time it printed a pause in the spreadsheet — but then kept running!

How can I stop this manually?

Any specific steps to reproduce the issue?

Click pause.

Oath of good faith

  • I, the author of this Issue, do solemnly swear that I’ve looked real hard for duplicate issues and I came up empty!!

melimchange

eudesdionatas

I always get these e-mails despite having paused the activity, I would like to stop this activity of copying. Is to much big, then I gave up. But the e-mails keep comming!

JamesKeating86

Are you requesting a feature or reporting a bug?

bug report

If reporting a bug, is there already an issue open for this same bug?

I have searched and others have mentioned the issue but i could not see any solution.

What is the current behavior?

copies files until it gets to three specific files where it shows errors:

  • Error: API call to drive.files.copy failed with error: This file cannot be copied by the authenticated user.. File: GDriveService (Copy Folder). Line: 93
  • Error: API call to drive.files.copy failed with error: File not found: . File: GDriveService (Copy Folder). Line: 93
  • Error: API call to drive.files.copy failed with error: File not found: . File: GDriveService (Copy Folder). Line: 93
    Then the copy process freezes. I have «continued» the process three times to the same results at the same three files.

What is the expected behavior?

continue the copy process

How would you reproduce the current behavior (if this is a bug)?

i have run the copy job over again a few times and these errors always occur on the same three files

Specify your

  • operating system: windows 10
  • browser: firefox

Any help hugely appreciated :)

Capture

shlomova

Bug summary

Error: API call to drive.files.copy failed with error: File not found: File_ID. File: GDriveService. Line: 93

Any specific steps to reproduce the issue?

Suggested possible explanation:
Error when copying from old folders from many years ago.
Link to a sample an old folder

Oath of good faith

  • [V] I, the author of this Issue, do solemnly swear that I’ve looked real hard for duplicate issues and I came up empty!!

Similar problems:
#54
#182 [not same]

julianmees

Hello, the first time I used Script in a folder, copied everything, it went well. But now I can not copy anymore, I have been trying for a long time and the time that I always put the Folder Link and advance to the other steps arriving at the end to copy the following error:

Oh no! Something went wrong
API call to drive.files.insert failed with error: File not found:

Only this appears, no error number reporting the problem.

Any solutions to this problem?

Seeker220

I copied a shared folder to My Drive, and only the shortcut was copied :(

mdoane1

Are you requesting a feature or reporting a bug?

Not that I know of.

If reporting a bug, is there already an issue open for this same bug?

Not that I have found.

What is the current behavior?

When trying to copy a folder, I receive this message: API call to drive.files.insert failed with error: File not found:

What is the expected behavior?

To copy the files as extected, as it has worked on many other folders and it’s contents of similar or even much larger sizes.

How would you reproduce the current behavior (if this is a bug)?

I would try to copy the folders that give me this error message, as it can be reproduced by doing so.

Specify your

  • operating system: WIndows 10 Education — Version 1809
  • browser: Google Chrome

greatvovan

As I understand, it is only the script that does all the work, however a Chrome Application is formally available in Chrome Web Store:

image

I clicked on «Add to Chrome», after which something happened and the browser opened a new tab. At the same time the «Add» button disappeared from the app’s page:

image

However Chrome does not list anything new in among the applications:

image

For purposes of keeping my browser clean I would like to know:

  1. Was anything installed in my browser when I clicked the «Add» button?
  2. If yes, why is it not listed and how to remove it?
  3. If no, why did the «Add» button disappear?

Bug summary

Status of the Chrome Application is not clear in browser’s settings.

Any specific steps to reproduce the issue?

  1. Open the application’s page.
  2. Click «Add to Chrome».
  3. Navigate to chrome://extensions/ and check the application list.

Oath of good faith

  • I, the author of this Issue, do solemnly swear that I’ve looked real hard for duplicate issues and I came up empty!!

maroc-cloud

Bug summary

On my own deployment — to change the time limits / paid Google Account.
After running 5h30 , the trigger copy failed with this error message :
Error: Cannot locate spreadsheet. Please try again.
at GDriveService.openSpreadsheet(GDriveService:130:23)
at copy(main:45:24)

Shouldn’t it be handle by try / retry ?

Apolla13

Are you requesting a feature or reporting a bug? Bug

If reporting a bug, is there already an issue open for this same bug? No

What is the current behavior? I successfully copied documents, but failed to copy all the comments that were within

What is the expected behavior? I expect that the documents (Documents, Spreadsheets etc)

How would you reproduce the current behavior (if this is a bug)? Don’t get the question

Specify your

  • operating system: MacOs
  • browser: Chrome

The situation is: I work mostly with Google Documents and Google Spreadsheets where users leave their notes in the comment section. But after copying I couldn’t find any of those comments. Copying comments with the file is vital for my work. Please, help

papyr

Hi @ericyd very nice add-on 👍

I followed the steps and gave permissions, after sharing the folders but I get an error, do you have any updates or idea on how to fix this


Error: There was an error initializing the copy folder request.
Error message: Exception: No item with the given ID could be found, or you do not have permission to access it..
Please try again. Make sure you have correct permissions to copy this folder, and make sure you are using Google Chrome or Chromium when using this app.

Ngocnguyen29192

Bug summary

Any specific steps to reproduce the issue?

Oath of good faith

  • I, the author of this Issue, do solemnly swear that I’ve looked real hard for duplicate issues and I came up empty!!

Dhanamerdeka

Hello dev
umm.. i think this script need a verify feature…
because at copying a lot of software and data… this script mostly get error at copying file
like… at some case… some folder or files not copied
so yeah….
i think it will be better to make a system where the script doublecheck two times on the end of it

and yeah i think it’s good too to adding feature like quota settings…. like… gsuite and another
like… dropdown quota setting manual… if the automatically doesn’t possible

yairwinmm

Can’t copy from Google Share Drive😥. It will be better if you can add a feature to copy from share drive or copy to share drive 🥺.

WvdW

Hi Eric,

Thanks for a great utility that has saved me lots of time and effort in managing my Google Drive!

Are you planning on adding any support for the new Google Team Drives? Currently the script can only access folders in your My Drive section and does not even display the Team Drives section, so folder structures there have to be created manually :(

Werner

evetaku

Error copy

Failed to save properties. This could affect script performance and may require restarting the copy. Error Message: API call to drive.files.update failed with error: User rate limit exceeded. File: GDriveService. Line: 73
Paused due to Google quota limits — copy will resume in 1-2 minutes

line73

its wil be resumeable ?

evetaku

i got this notice Script has reached daily maximum run time of 90 minutes. Script must pause for 24 hours to reset Google Quotas, and will resume at that time. For more information, please see https://developers.google.com/apps-script/guides/services/quotas

but today after 24 hours, not resume from last update ? i need using manual resume menu or still waiting ? Because status its still on working.

not auto resume

У меня есть файл Excel (.xlsm) как вложение Gmail в моем почтовом ящике, и я хочу передать его в GDrive. Там он должен быть сохранен как GSheet. Я пытаюсь автоматизировать этот процесс с помощью скрипта приложений.

К сожалению, при запуске скрипта возникает ошибка. (Вызов API для drive.files.insert завершился ошибкой: неверный запрос) Это очень странно, потому что несколько раз скрипт срабатывает, и файл может быть преобразован без каких-либо проблем. На прошлой неделе это сработало, как только я отправил письмо с вложением кому-то (не спрашивайте меня, где контекст). Но теперь это история, и я не знаю, как исправить ошибку.

Я новичок в StackOverflow и с нетерпением жду каждого вашего ответа. Большое спасибо.

Вот код:

function importFunction() {

  var threads =  GmailApp.search('CC520_Report_Lukas_GAS_ABC');                             
  var messages = threads[0].getMessages();    
  var message = messages[0];                                                                
  var attachment = message.getAttachments()[0];                                            

  var resource = {
    title: 'NewFileLukas',                                
    mimeType: MimeType.GOOGLE_SHEETS,
    parents: [{id: 'xxxxx6BD1SIfI0Cz5bmGahzSlHUxxxxxx'}], 
};

var insert = Drive.Files.insert(resource, attachment);      // Here comes the error. 

1 ответ

Лучший ответ

Я верю вашей цели следующим образом.

  • Вы хотите преобразовать файл .xlsm в электронную таблицу Google.
  • attachment, который вы используете, — это файл .xlsm.
  • В вашей ситуации ошибка API call to drive.files.insert failed with error: Bad Request возникает в Drive.Files.insert(resource, attachment).
    • Вы хотите удалить эту ошибку.

Для этого как насчет этого ответа? У меня тоже была такая же проблема.

Пункты модификации:

  • Тип mimeType файла .xlsmapplication/vnd.ms-excel.sheet.macroenabled.12. В вашем сценарии, когда используется console.log(attachment.getContentType()), если attachment является файлом .xlsm, возвращается такой тип mimeType.
  • Когда importFormats подтвержден методом «About: get» в Drive API Ref, похоже, что application/vnd.ms-excel.sheet.macroenabled.12 можно преобразовать в application/vnd.google-apps.spreadsheet. Это можно увидеть в Drive API v2 и v3.
    • Но когда данные application/vnd.ms-excel.sheet.macroenabled.12 используются для Drive.Files.insert(resource, attachment), возникает ошибка. В этом случае я подтвердил, что даже когда я тестировал это с помощью Drive API v3, возникла та же проблема.
    • Я подумал, что это преобразование еще не отразилось. Также я считаю, что это будет изменено в будущем обновлении.

В качестве текущего обходного пути я хотел бы предложить преобразовать файл .xlsm в электронную таблицу Google, изменив mimeType большого двоичного объекта.

Измененный скрипт:

Когда ваш скрипт будет изменен, пожалуйста, измените его следующим образом.

var attachment = message.getAttachments()[0];
var attachment = message.getAttachments()[0].setContentType(MimeType.MICROSOFT_EXCEL);

Или

var attachment = message.getAttachments()[0];
if (attachment.getContentType() == "application/vnd.ms-excel.sheet.macroenabled.12") {
  attachment.setContentType(MimeType.MICROSOFT_EXCEL);
}

Заметка:

  • В моей среде я мог подтвердить, что, изменив mimeType на MimeType.MICROSOFT_EXCEL, файл .xlsm можно преобразовать в электронную таблицу Google.
  • В этом случае макрос файла .xlsm не преобразуется в скрипт Google Apps. Кроме того, после преобразования файла .xlsm в электронную таблицу Google, когда таблица Google преобразуется в файл Excel, макрос не включается. Думаю, это спецификация. Так что будьте осторожны.

Справка:

  • setContentType (contentType)


1

Tanaike
29 Апр 2020 в 12:38

Insert a new file.
Try it now or see an example.

This method supports an /upload URI and accepts uploaded media with the following characteristics:

  • Maximum file size: 5120GB
  • Accepted Media MIME types:
    */*

Note: Specify a valid MIME type, rather than the literal */* value. The literal */* is only used to indicate that any valid MIME type can be uploaded.

Apps creating shortcuts with files.insert must specify the MIME type application/vnd.google-apps.shortcut.

Apps should specify a file extension in the title property when inserting files with the API. For example, an operation to insert a JPEG file should specify something like "title": "cat.jpg" in the metadata.

Subsequent GET requests include the read-only fileExtension property populated with the extension originally specified in the title property. When a Google Drive user requests to download a file, or when the file is downloaded through the sync client, Drive builds a full filename (with extension) based on the title. In cases where the extension is missing, Google Drive attempts to determine the extension based on the file’s MIME type.

Request

HTTP request

This method provides media upload functionality through two separate URIs. For more details, see the document on media upload.

  • Upload URI, for media upload requests:
    POST https://www.googleapis.com/upload/drive/v2/files
  • Metadata URI, for metadata-only requests:
    POST https://www.googleapis.com/drive/v2/files

Parameters

Parameter name Value Description
Required query parameters
uploadType string The type of upload request to the /upload URI. If you
are uploading data (using an /upload URI), this field is
required. If you are creating a metadata-only file, this field is not
required. Additionally, this field is not shown in the «Try this API»
widget because the widget doesn’t support data uploads.
Acceptable values are:

  • media — Simple upload. Upload the media only, without any metadata.
  • multipart — Multipart upload. Upload both the media and its metadata, in a single request.
  • resumable — Resumable upload. Upload the file in a resumable fashion, using a series of at least two requests where the first request includes the metadata.
Optional query parameters
convert boolean Whether to convert this file to the corresponding Docs Editors format.

(Default: false)

enforceSingleParent boolean Deprecated. Creating files in multiple folders is no longer supported.

(Default: false)

includeLabels string A comma-separated list of IDs of labels to include in the labelInfo part of the response.

includePermissionsForView string Specifies which additional view’s permissions to include in the response. Only ‘published’ is supported.

ocr boolean Whether to attempt OCR on .jpg, .png, .gif, or .pdf uploads.

(Default: false)

ocrLanguage string If ocr is true, hints at the language to use. Valid values are BCP 47 codes.

pinned boolean Whether to pin the head revision of the uploaded file. A file can have a maximum of 200 pinned revisions.

(Default: false)

supportsAllDrives boolean Whether the requesting application supports both My Drives and shared drives.

(Default: false)

supportsTeamDrives boolean Deprecated use supportsAllDrives instead.

(Default: false)

timedTextLanguage string The language of the timed text.

timedTextTrackName string The timed text track name.

useContentAsIndexableText boolean Whether to use the content as indexable text.

(Default: false)

visibility string The visibility of the new file. This parameter is only relevant when convert=false.

Acceptable values are:

  • «DEFAULT«: The visibility of the new file is determined by the user’s default visibility/sharing policies.
    (default)
  • «PRIVATE«: The new file will be visible to only the owner.

Authorization

This request requires authorization with at least one of the following scopes:

Scope
https://www.googleapis.com/auth/drive
https://www.googleapis.com/auth/drive.file
https://www.googleapis.com/auth/drive.appdata
https://www.googleapis.com/auth/drive.apps.readonly

Some scopes are restricted and require a security assessment for your app to use them. For more information, see the authentication and authorization page.

Request body

In the request body, supply a Files resource with the following properties as the metadata. For more information, see the document on media upload.

Property name Value Description Notes
Optional Properties
contentRestrictions[].readOnly boolean Whether the content of the file is read-only. If a file is read-only, a new revision of the file may not be added, comments may not be added or modified, and the title of the file may not be modified. writable
contentRestrictions[].reason string Reason for why the content of the file is restricted. This is only mutable on requests that also set readOnly=true. writable
copyRequiresWriterPermission boolean Whether the options to copy, print, or download this file, should be disabled for readers and commenters. writable
description string A short description of the file. writable
folderColorRgb string Folder color as an RGB hex string if the file is a folder or a shortcut to a folder. The list of supported colors is available in the folderColorPalette field of the About resource. If an unsupported color is specified, it will be changed to the closest color in the palette. writable
id string The ID of the file. writable
indexableText.text string The text to be indexed for this file. writable
labels.starred boolean Whether this file is starred by the user. writable
labels.trashed boolean Whether the file has been trashed, either explicitly or from a trashed parent folder. Only the owner may trash a file. The trashed item is excluded from all files.list responses returned for any user who does not own the file. However, all users with access to the file can see the trashed item metadata in an API response. All users with access can copy, download, export, and share the file. writable
labels.viewed boolean Whether this file has been viewed by this user. writable
lastViewedByMeDate datetime Last time this file was viewed by the user (formatted RFC 3339 timestamp). writable
mimeType string The MIME type of the file. This is only mutable on update when uploading new content. This field can be left blank, and the mimetype will be determined from the uploaded content’s MIME type. writable
modifiedDate datetime Last time this file was modified by anyone (formatted RFC 3339 timestamp). This is only mutable on update when the setModifiedDate parameter is set. writable
originalFilename string The original filename of the uploaded content if available, or else the original value of the title field. This is only available for files with binary content in Google Drive. writable
parents[] list Collection of parent folders which contain this file.

If not specified as part of an insert request, the file will be placed directly in the user’s My Drive folder. If not specified as part of a copy request, the file will inherit any discoverable parents of the source file. Update requests can also use the addParents and removeParents parameters to modify the parents list.

writable
properties[] list The list of properties. writable
shortcutDetails.targetId string The ID of the file that this shortcut points to. writable
title string The title of this file. Note that for immutable items such as the top level folders of shared drives, My Drive root folder, and Application Data folder the title is constant. writable
writersCanShare boolean Whether writers can share the document with other users. Not populated for items in shared drives. writable

Response

If successful, this method returns a Files resource in the response body.

Examples

Note: The code examples available for this method do not represent all supported programming languages (see the client libraries page for a list of supported languages).

Java

Uses the Java client library.

import com.google.api.client.http.FileContent;
import com.google.api.services.drive.Drive;
import com.google.api.services.drive.model.File;
import com.google.api.services.drive.model.ParentReference;

import java.io.IOException;
import java.util.Arrays;
// ...

public class MyClass {

  // ...

  /**
   * Insert new file.
   *
   * @param service Drive API service instance.
   * @param title Title of the file to insert, including the extension.
   * @param description Description of the file to insert.
   * @param parentId Optional parent folder's ID.
   * @param mimeType MIME type of the file to insert.
   * @param filename Filename of the file to insert.
   * @return Inserted file metadata if successful, {@code null} otherwise.
   */
  private static File insertFile(Drive service, String title, String description,
      String parentId, String mimeType, String filename) {
    // File's metadata.
    File body = new File();
    body.setTitle(title);
    body.setDescription(description);
    body.setMimeType(mimeType);

    // Set the parent folder.
    if (parentId != null && parentId.length() > 0) {
      body.setParents(
          Arrays.asList(new ParentReference().setId(parentId)));
    }

    // File's content.
    java.io.File fileContent = new java.io.File(filename);
    FileContent mediaContent = new FileContent(mimeType, fileContent);
    try {
      File file = service.files().insert(body, mediaContent).execute();

      // Uncomment the following line to print the File ID.
      // System.out.println("File ID: " + file.getId());

      return file;
    } catch (IOException e) {
      System.out.println("An error occurred: " + e);
      return null;
    }
  }

  // ...
}

.NET

Uses the .NET client library.

using Google.Apis.Drive.v2;
using Google.Apis.Drive.v2.Data;
using Google.Apis.Requests;
using System.Collections.Generic;
using System.Net;

// ...

public class MyClass {

  // ...

  /// <summary>
  /// Insert new file.
  /// </summary>
  /// <param name="service">Drive API service instance.</param>
  /// <param name="title">Title of the file to insert, including the extension.</param>
  /// <param name="description">Description of the file to insert.</param>
  /// <param name="parentId">Parent folder's ID.</param>
  /// <param name="mimeType">MIME type of the file to insert.</param>
  /// <param name="filename">Filename of the file to insert.</param>
  /// <returns>Inserted file metadata, null is returned if an API error occurred.</returns>
  private static File insertFile(DriveService service, String title, String description, String parentId, String mimeType, String filename) {
    // File's metadata.
    File body = new File();
    body.Title = title;
    body.Description = description;
    body.MimeType = mimeType;

    // Set the parent folder.
    if (!String.IsNullOrEmpty(parentId)) {
      body.Parents = new List<ParentReference>()
          {new ParentReference() {Id = parentId}};
    }

    // File's content.
    byte[] byteArray = System.IO.File.ReadAllBytes(filename);
    MemoryStream stream = new MemoryStream(byteArray);

    try {
      FilesResource.InsertMediaUpload request = service.Files.Insert(body, stream, mimeType);
      request.Upload();

      File file = request.ResponseBody;

      // Uncomment the following line to print the File ID.
      // Console.WriteLine("File ID: " + file.Id);

      return file;
    } catch (Exception e) {
      Console.WriteLine("An error occurred: " + e.Message);
      return null;
    }
  }

  //...

}

PHP

Uses the PHP client library.

/**
 * Insert new file.
 *
 * @param Google_Service_Drive $service Drive API service instance.
 * @param string $title Title of the file to insert, including the extension.
 * @param string $description Description of the file to insert.
 * @param string $parentId Parent folder's ID.
 * @param string $mimeType MIME type of the file to insert.
 * @param string $filename Filename of the file to insert.
 * @return Google_Service_Drive_DriveFile The file that was inserted. NULL is
 *     returned if an API error occurred.
 */
function insertFile($service, $title, $description, $parentId, $mimeType, $filename) {
  $file = new Google_Service_Drive_DriveFile();
  $file->setTitle($title);
  $file->setDescription($description);
  $file->setMimeType($mimeType);

  // Set the parent folder.
  if ($parentId != null) {
    $parent = new Google_Service_Drive_ParentReference();
    $parent->setId($parentId);
    $file->setParents(array($parent));
  }

  try {
    $data = file_get_contents($filename);

    $createdFile = $service->files->insert($file, array(
      'data' => $data,
      'mimeType' => $mimeType,
    ));

    // Uncomment the following line to print the File ID
    // print 'File ID: %s' % $createdFile->getId();

    return $createdFile;
  } catch (Exception $e) {
    print "An error occurred: " . $e->getMessage();
  }
}

Python

Uses the Python client library.

from apiclient import errors
from apiclient.http import MediaFileUpload
# ...

def insert_file(service, title, description, parent_id, mime_type, filename):
  """Insert new file.

  Args:
    service: Drive API service instance.
    title: Title of the file to insert, including the extension.
    description: Description of the file to insert.
    parent_id: Parent folder's ID.
    mime_type: MIME type of the file to insert.
    filename: Filename of the file to insert.
  Returns:
    Inserted file metadata if successful, None otherwise.
  """
  media_body = MediaFileUpload(filename, mimetype=mime_type, resumable=True)
  body = {
    'title': title,
    'description': description,
    'mimeType': mime_type
  }
  # Set the parent folder.
  if parent_id:
    body['parents'] = [{'id': parent_id}]

  try:
    file = service.files().insert(
        body=body,
        media_body=media_body).execute()

    # Uncomment the following line to print the File ID
    # print 'File ID: %s' % file['id']

    return file
  except errors.HttpError, error:
    print 'An error occurred: %s' % error
    return None

JavaScript

Uses the JavaScript client library.

/**
 * Insert new file.
 *
 * @param {File} fileData File object to read data from.
 * @param {Function} callback Function to call when the request is complete.
 */
function insertFile(fileData, callback) {
  const boundary = '-------314159265358979323846';
  const delimiter = "rn--" + boundary + "rn";
  const close_delim = "rn--" + boundary + "--";

  var reader = new FileReader();
  reader.readAsBinaryString(fileData);
  reader.onload = function(e) {
    var contentType = fileData.type || 'application/octet-stream';
    var metadata = {
      'title': fileData.fileName,
      'mimeType': contentType
    };

    var base64Data = btoa(reader.result);
    var multipartRequestBody =
        delimiter +
        'Content-Type: application/jsonrnrn' +
        JSON.stringify(metadata) +
        delimiter +
        'Content-Type: ' + contentType + 'rn' +
        'Content-Transfer-Encoding: base64rn' +
        'rn' +
        base64Data +
        close_delim;

    var request = gapi.client.request({
        'path': '/upload/drive/v2/files',
        'method': 'POST',
        'params': {'uploadType': 'multipart'},
        'headers': {
          'Content-Type': 'multipart/mixed; boundary="' + boundary + '"'
        },
        'body': multipartRequestBody});
    if (!callback) {
      callback = function(file) {
        console.log(file)
      };
    }
    request.execute(callback);
  }
}

Go

Uses the Go client library.

import (
  "google.golang.org/drive/v2"
  "fmt"
)

// InsertFile creates a new file in Drive from the given file and details
func InsertFile(d *drive.Service, title string, description string,
    parentId string, mimeType string, filename string) (*drive.File, error) {
  m, err := os.Open(filename)
  if err != nil {
    fmt.Printf("An error occurred: %vn", err)
    return nil, err
  }
  f := &drive.File{Title: title, Description: description, MimeType: mimeType}
  if parentId != "" {
    p := &drive.ParentReference{Id: parentId}
    f.Parents = []*drive.ParentReference{p}
  }
  r, err := d.Files.Insert(f).Media(m).Do()
  if err != nil {
    fmt.Printf("An error occurred: %vn", err)
    return nil, err
  }
  return r, nil
}

Objective-C

Uses the Objective-C client library.

#import "GTLDrive.h"
// ...

+ (void)insertFileWithService:(GTLServiceDrive *)service
                        title:(NSString *)title
                  description:(NSString *)description
                     parentId:(NSString *)parentId
                     mimeType:(NSString *)mimeType
                         data:(NSData *)data
              completionBlock:(void (^)(GTLDriveFile *, NSError *))completionBlock {
  GTLDriveFile *file = [GTLDriveFile object];

  file.title = title;
  file.descriptionProperty = description;
  file.mimeType = mimeType;

  if (parentId != null) {
    file.parents = [NSArray arrayWithObjects: parentId, nil];
  }

  GTLUploadParameters *uploadParameters =
    [GTLUploadParameters uploadParametersWithData:data MIMEType:mimeType];
  GTLQueryDrive *query =
    [GTLQueryDrive queryForFilesInsertWithObject:file
                                uploadParameters:uploadParameters];

  // queryTicket can be used to track the status of the request, more information can
  // be found on <a href="https://code.google.com/p/google-api-objectivec-client/wiki/Introduction#Uploading_Files">https://code.google.com/p/google-api-objectivec-client/wiki/Introduction#Uploading_Files</a>
  GTLServiceTicket *queryTicket =
    [service executeQuery:query
        completionHandler:^(GTLServiceTicket *ticket,
                            GTLDriveFile *insertedFile, NSError *error) {
        if (error == nil) {
          // Uncomment the following line to print the File ID.
          // NSLog(@"File ID: %@", insertedFile.identifier);
          completionBlock(insertedFile, nil);
        } else {
          NSLog(@"An error occurred: %@", error);
          completionBlock(nil, error);
        }
      }];
}

// ...

Try it!

Note: APIs Explorer currently supports metadata requests only.

Use the APIs Explorer below to call this method on live data and see the response.

Environment Details

If a workflow fails because a file was not found, it can be discouraging.  In this article, we cover some of the best practices to prevent this error as well as some troubleshooting tips if it occurs despite best practices being followed.


 

Error: Can’t find the file: “[pathFileName]”. Make sure the file path is correct.

In versions prior to 2021.1.4, you will see the shorter message

Error: File not found "[pathFileName]"
  • Alteryx Designer or Alteryx Server or Alteryx Analytic Hub
    • All versions
  • This error can occur associated with a range of tools, but the most common are Input Data, Output Data, or Dynamic Input tool.

Cause

Alteryx cannot access one or more files that the workflow requires.

Resolution

First, verify that the file is specified correctly in the tool.

  1. Check that the file is in the expected location.
  2. Verify that the file name has been specified accurately, including file type extension.

Next, make sure that Alteryx is configured to have access to the location.

  1. In the above example image, the path to the desired workflow includes a mapped drive letter (Z:)  This is not the best way to designate a path when writing a workflow.  Instead, best practice is to use a UNC path.  A UNC path has a format that gives the hostname as well as the directory structure in which the desired file is located, for example 
     \HostnameDOTdomainDOTcomMainDirectoryNameSubDirectoriesFilename.csv

     

  2. If you have used a mapped drive letter instead of a UNC path, the workflow will probably run correctly from your desktop Designer because you are running from your own account, but this is not the best practice because if you ever share your workflow with a colleague or schedule it to run automatically or publish it to a gallery, you’ll find that running the workflow in the new environment causes it to fail.  You can change the paths in your workflow using Options > Advanced Options > Workflow Dependencies.

     
  3. You can use the All UNC button to change the paths to UNC paths, and if you desire, you can also test the location to confirm.   Click OK to make the change in the workflow.

  4. In the scenarios noted above, the colleague or the AlteryxService must have permission to access network shared resources, even with the UNC path.  There is more information on configuring Desktop Automation or Server to grant appropriate permissions in other articles.

 More subtle considerations

  1. The path length cannot be longer than 260 characters.
  2. If the workflow is running from a gallery or has been scheduled, then there are a few more restrictions.  That is covered in a separate article:  Error: File not Found in Staging Directory

Additional Resources

  • Designer Help: Workflow Dependencies
  • Configure Desktop with Scheduler
  • Server Help: Configure Required Run As User Permissions

Понравилась статья? Поделить с друзьями:
  • B2109 ошибка infiniti
  • Api authentication error
  • B1822 ошибка тойота
  • Api 404 ошибка
  • B1491 ошибка asx