Home > Net >  Multipart/mixed request for google drive bulk deletion using request npm package
Multipart/mixed request for google drive bulk deletion using request npm package

Time:12-17

I was trying to do bulk deletion of files from google drive using rest API. So i was framing the request for bulk deletion request i was able to achieve the deletion with the similar request framing method Bulk delete files on Google Drive with raw XMLHttpRequest but i was trying to achieve this without sending the body instead of sending multipart array in the request object. I am getting error 400 with following response body

<HEAD>
<TITLE>Bad Request</TITLE>
</HEAD>
<BODY BGCOLOR="#FFFFFF" TEXT="#000000">
<H1>Bad Request</H1>
<H2>Error 400</H2>
</BODY>
</HTML>

This is my request object which is failing

const _multipart = []
  arrayOfFileIds.forEach((current) => {
    const obj = {
      body: 'Content-Type: application/http\n\n'  
      'DELETE https://www.googleapis.com/drive/v3/files/'  
      current   '\nAuthorization: Bearer '   authToken
    }
    _multipart.push(obj)
  })

  const requestOptions = {
    url: 'https://www.googleapis.com/batch/drive/v3',
    method: 'POST',
    headers: {
      'Content-Type': 'multipart/mixed'
    },
    multipart: _multipart
  }

And below request Object is working

  const boundary = 'END_OF_PART'
  const separation = '\n--'   boundary   '\n'
  const ending = '\n--'   boundary   '--'
  const requestBody = arrayOfFileIds.reduce((accum, current) => {
    accum  = separation  
    'Content-Type: application/http\n\n'  
    'DELETE https://www.googleapis.com/drive/v3/files/'  
    current  
    '\nAuthorization: Bearer '   authToken
    return accum
  }, '')   ending


  const requestOptions = {
    url: 'https://www.googleapis.com/batch/drive/v3',
    method: 'POST',
    headers: {
      'Content-Type': 'multipart/mixed; boundary='   boundary

    },
    body: requestBody
    multipart: _multipart
  }

CodePudding user response:

Modification points:

  • The access token can be included in the request header.
  • Put Content-Type of each batch request out of body.

When these points are reflected to your script, it becomes as follows.

Modified script:

const _multipart = [];
arrayOfFileIds.forEach((current) => {
  const obj = {
    "Content-Type": "application/http",
    body: "DELETE https://www.googleapis.com/drive/v3/files/"   current   "\n",
  };
  _multipart.push(obj);
});

const requestOptions = {
  url: "https://www.googleapis.com/batch/drive/v3",
  method: "POST",
  headers: {
    "Content-Type": "multipart/mixed",
    Authorization: "Bearer "   authToken,
  },
  multipart: _multipart,
};

Note:

  • When I tested the above modified script, no error occurs. The files can be deleted. When you tested the above script, when an error occurs, please confirm the script and the access token, again.

Reference:

  • Related