Как взять fs.createWriteStream и загрузить его в Gapi api google drive create function?

#javascript #node.js #google-drive-api #google-api-js-client

#javascript #node.js #google-drive-api #google-api-js-client

Вопрос:

У меня есть расширение Chrome, которое берет информацию о файле из серверной части node.js сервер для того, чтобы обслуживать файлы Google Drive внутри расширения. В данном конкретном случае у меня возникают проблемы с загрузкой файла, сохраненного на серверной части, в клиент gapi на интерфейсе, который позволяет пользователю загружать его на свой Google Диск. Аутентификация и все в порядке, основная проблема заключается в загрузке.

Вот мой код.

background.js (на стороне клиента):

   var parentFolder;
  var fileArray;
  let classroomUrl = 'https://connect.smartpathed.com/getclassroomparent';
  await fetch(classroomUrl)
  .then(response => response.text())
  .then(data => parentFolder = data)
  .then(data => console.log(parentFolder));
  let fileArrayUrl = "https://connect.smartpathed.com/getclassroomarrayselect";
  await fetch(fileArrayUrl)
  .then(response => response.json())
  .then(data => fileArray = data)
  .then(data => console.log(fileArray));
  function sleep(milliseconds) {
    const date = Date.now();
    let currentDate = null;
    do {
      currentDate = Date.now();
    } while (currentDate - date < milliseconds);
  }
  gapi.client.init({
    apiKey: API_KEY,
    discoveryDocs: DISCOVERY_DOCS,
  }).then(function() {
    chrome.identity.getAuthToken({interactive: true}, async function(token) {
      gapi.auth.setToken({
        'access_token': token,
      });
      for(var i = 0; i < fileArray.length; i  ) {
      if (fileArray[i].type != "folder") {
      const fileNameFile = fileArray[i].name;
      const typeFile = fileArray[i].type;
      const descriptionFile = fileArray[i].description;
      let newType = ''
      if(typeFile === 'docx') {
        newType = 'application/vnd.openxmlformats-officedocument.wordprocessingml.document'
      }
      if(typeFile === 'pptx') {
        newType = 'application/vnd.google-apps.presentation'
      }
      if(typeFile === 'xlsx') {
        newType = 'application/vnd.google-apps.spreadsheet'
      }
      if(typeFile === 'pdf') {
        newType = 'application/pdf'
      }
      var destFile = './src/Pages/downloads/'   fileNameFile   '.'   typeFile;
      var newId = ''
      var fileMetadata = {
        'name': fileNameFile,
        'description': descriptionFile,
        'parents': [parentFolder]
      };
      console.log(fileMetadata)
      var media;
      await fetch('https://connect.smartpathed.com/makefile', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json', Accept: 'application/json' },
        body: JSON.stringify({
          newType: newType,
          fileDest: destFile,
        })
      })
      .then(() => {
        alert('next step activated')
        fetch('https://connect.smartpathed.com/getfile')
        .then(res => res.json)
        .then(data => media = data)
        .then(data => console.log("this is the body of topfile: "   data))
        }) 
      gapi.client.drive.files.create({
        resource: fileMetadata,
        media: media,
        fields: 'id'
      })
      .then(function (err, file) {
        if (err) {
          console.log("Error for file creation: "   JSON.stringify(err));
          console.log(media);
        } else {
          console.log("file download complete."   file);
          newId = file.id;
        } 
      })
    }
 

Запросы Post (Node.js серверная часть):

   app.post('/makefile', (req, res) => {
  const newType = req.body.newType;
  console.log("this is the file type in post request: "   newType);
  const dest = req.body.fileDest;
  console.log("this is the file destination: "   dest);

  var media = {
    mimeType: newType,
    body: fs.createReadStream(dest),
  };

  app.set("media", media);

})

app.get("/getfile", (req, res) => {
  const file = req.app.get('media');
  console.log(file);
  res.send(file);
})
 

Весь этот код работает нормально, пока не доходит до запроса мультимедиа и последующего создания файла через drive.files.create. Я знаю, что fs.createReadStream работает на серверной части и что информация передается, потому что я могу видеть это в журнале. Однако я не знаю, возможно ли вообще передать тело fs.createReadStream на сторону клиента и иметь возможность использовать его в запросе мультимедиа в функции google.drive.create. Это может быть просто невозможно из-за проблем с путями.

С учетом сказанного, есть ли какой-либо способ достичь того, чего я пытаюсь достичь здесь, то есть передать media var на сторону клиента, чтобы разрешить загрузку тела файла, сохраненного на серверной части, через gapi?

Рад уточнить, нужно ли для этого больше контекста.

Комментарии:

1. Разве вы не можете просто создать большой двоичный объект на серверной части и отправить его в двоичном формате, а затем загрузить его? developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest / … — какие ошибки вы получаете?