Google Drive v3.Nodejs Resumable Upload создает файл без названия в неправильном каталоге - PullRequest
0 голосов
/ 25 февраля 2019

Эй, я следовал инструкциям из краткого руководства по Drive и сгенерировал token.json, используя следующие области действия:

const SCOPES = [
  'https://www.googleapis.com/auth/drive',
  'https://www.googleapis.com/auth/drive.appdata',
  'https://www.googleapis.com/auth/drive.file'
];

Затем я запускаю следующий код, чтобы попытаться создать / загрузить файлв Google Drive.

    async function testing() {
  let driveFolder = 'FOLDERID';
  let res;
  try {
    const oauth2Client = new google.auth.OAuth2(
      credentials.client_id,
      credentials.client_secret,
      credentials.redirect_uris
    );
    await oauth2Client.setCredentials({
      ...tokenInfo
    });

    console.log('=== completed drive authentication', oauth2Client);
    const drive = await google.drive({
      version: 'v3',
      auth: await oauth2Client
    });
    console.log('=== Initialised Drive API');
    res = await drive.files.create({
      parameters :{
        uploadType: 'resumable'
      },
      requestBody: {
        name: 'Testing.txt',
        mimeType: 'text/plain',
        parents: [driveFolder]
      },
      media: {
        mimeType: 'text/plain',
        body: 'Hello world!!!'
      }
    });
    console.log('=== Completed Report UPLOAD:', res);
    return;
  } catch (err) {
    console.error('ERROR: \n', err);
  }
}

Запрос завершается, не обнаружив ошибки, но ответ, который возвращается, не определен.Последние два журнала показывают следующее

=== completed drive authentication OAuth2Client {
  _events: [Object: null prototype] {},
  _eventsCount: 0,
  _maxListeners: undefined,
  transporter: DefaultTransporter {},
  credentials:
   { access_token:
      'ACCESS TOKEN STRING',
     refresh_token:
      'REFRESH TOKEN STRING',
     scope:
      'https://www.googleapis.com/auth/drive.file https://www.googleapis.com/auth/drive https://www.googleapis.com/auth/drive.appdata',
     token_type: 'Bearer',
     expiry_date: 1551070810157 },
  certificateCache: null,
  certificateExpiry: null,
  refreshTokenPromises: Map {},
  _clientId:'CLIENT ID STRING VALUE',
  _clientSecret: 'CLIENT SECRET VALUE',
  redirectUri: [ 'REDIRECT URL', 'http://localhost' ],
  authBaseUrl: undefined,
  tokenUrl: undefined,
  eagerRefreshThresholdMillis: 300000 }
=== Initialised Drive API
=== Completed Report UPLOAD: undefined

1 Ответ

0 голосов
/ 25 февраля 2019

Вы можете попробовать быстрый запуск с помощью NodeJS из документации:

// change the scopes
        const SCOPES = [  'https://www.googleapis.com/auth/drive',
        'https://www.googleapis.com/auth/drive.appdata',
        'https://www.googleapis.com/auth/drive.file'];

function uploadFile(auth){
    var drive = google.drive('v3');
    var fileMetadata = {
           'name': 'Some.jpg' // name of the file
        };
    var media = {
            mimeType: 'image/jpeg',
            resumable: true,
            //PATH OF THE FILE FROM YOUR COMPUTER
            body: fs.createReadStream('/usr/local/google/home/malicdemj/Desktop/blue-cyber-future-technology-concept-background_42077-488.jpg')
        };

        drive.files.create({
            auth: auth,
            resource: fileMetadata,
            media: media,
            fields: 'id'
        }, function (err, file) {
        if (err) {
            // Handle error
            console.error(err);
        } else {
            console.log('File Id: ', file.data.id);
        }
     });
  }

Загруженный файл на моем диске:

enter image description here

Также, пожалуйста, проверьте это ТАК сообщение для более подробной информации.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...