2021-02-27

How to take fs.createWriteStream and upload it to Gapi google drive api create function?

I have a chrome extension that takes file information from a backend node.js server in order to serve google drive files up within the extension. What I am having trouble with in this specific instance is uploading a file saved on the backend to a gapi client on the front end that allows a user to upload it to their google drive. The authentication and everything is fine, the main problem is the upload.

Here is my code.

background.js(client side):

  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 requests(Node.js back end):

  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);
})

All of this code works fine until it comes to the media request, and the subsequent file creation through drive.files.create. I know that the fs.createReadStream works on the back end, and that the information transfers over, because I am able to see it in the log. I don't, however, know if it is even possible to transfer an fs.createReadStream body to the client side, and be able to use it in the media request in the google.drive.create function. It could just not be possible due to pathing issues.

With that said, is there any way to achieve what I am trying to achieve here, that being the transfer of the media var to the client side to allow the body of the file saved on the backend to be uploaded through gapi?

Glad to clarify if this needs more context.



from Recent Questions - Stack Overflow https://ift.tt/3q3oeJz
https://ift.tt/eA8V8J

No comments:

Post a Comment