簡體   English   中英

從 Google Drive 下載文件並使用 NodeJS 上傳到 S3

[英]Download file from Google Drive and upload to S3 using NodeJS

我根據文檔從 Google 驅動器下載了我的 PDF 文件:

const file = await this.driveClient.files.get(
  {
    fileId: id,
    alt: 'media',
  },
  {
    responseType: 'stream'
  },
);

然后我構造一個表單數據:

const formData = new FormData();
formData.append('file', file.data, 'file.pdf');

並通過預簽名上傳 url將其發送到 S3:

const uploadedDocument = await axios({
  method: 'put',
  url: presignedS3Url,
  data: formData,
  headers: formData.getHeaders(),
});

該流程有效,但上傳到 s3 的文件顯示已損壞: 在此處輸入圖像描述

我還嘗試了來自 Google API 的不同響應類型,例如blob 知道我缺少什么嗎? 提前致謝!

您需要從谷歌驅動器將文件導出為 PDF,使用以下 function,傳遞 id:

/**
 * Download a Document file in PDF format
 * @param{string} fileId file ID
 * @return{obj} file status
 * */
async function exportPdf(fileId) {
  const {GoogleAuth} = require('google-auth-library');
  const {google} = require('googleapis');

  // Get credentials and build service
  // TODO (developer) - Use appropriate auth mechanism for your app
  const auth = new GoogleAuth({scopes: 'https://www.googleapis.com/auth/drive'});
  const service = google.drive({version: 'v3', auth});

  try {
    const result = await service.files.export({
      fileId: fileId,
      mimeType: 'application/pdf',
    });
    console.log(result.status);
    return result;
  } catch (err) {
    console.log(err)
    throw err;
  }
}

我設法通過將 stream 轉換為緩沖區並在不使用Formdata的情況下調用預簽名的 S3 URL 來解決該問題:

streamToBuffer(stream) {
  return new Promise((resolve, reject) => {
    const chunks = [];
    stream
      .on('data', (chunk) => {
        chunks.push(chunk);
      })
      .on('end', () => {
        resolve(Buffer.concat(chunks));
      })
      .on('error', reject);
  });
}

async uploadFileToS3(fileStream, signedUrl, contentType) {
  const data = await this.streamToBuffer(fileStream);

  const response = await axios.put(signedUrl, data, {
    headers: {
      'Content-Type': contentType,
    },
  });

  return response;
}

const file = await this.driveClient.files.get(
  {
    fileId: id,
    alt: 'media',
  },
  {
    responseType: 'stream'
  },
);

const uploadedDocument = await this.uploadFileToS3(
  file.data,
  s3Url,
  file.mimeType
);

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM