Skip to content Skip to sidebar Skip to footer

Angular 2+ HTTP POST And GDrive API. Resumable File Upload With Name

I am trying to upload files to Google Drive in Angular 2. So far I am able to upload files, but without title and they are 'Untitled' Here is code to do that: gDriveUploader(file):

Solution 1:

So. A bit more research on how API works. I came up with the following solution for resumable file upload. Main Idea, that first time I have to make a request and "set metadata" for my file and get response with the link, where to upload the file. And this link came as one of the response header called location.

Here is fully working code. Just pass File object to the first function.

I just quickly made 2 functions for this. First one will set metadata (just name) and call second function to upload just binary data.

gDriveUploader(file): Promise<any> {
  let authToken = token
  const url = `https://www.googleapis.com/upload/drive/v3/files?uploadType=resumable`
      let headers = new Headers({
        'Authorization': 'Bearer ' + authToken,
        'Content-Type': 'application/json; charset=UTF-8',
      });
      let options = new RequestOptions ({ 
        headers: headers,
      });
      return this.http.post(`${url}`, {name: file.fullName}, options) //just set the name
          .toPromise()
            .then(response => this.gDriveUploadFile(file, response.headers.get('location'))) //call second function to upload `file` to proper URI from response
            .then(response => {
                let id = response.json().id //parse id of uploaded file
                let resp = {fileName: file.fullName, fileType: file.fileType, fileSize: file.size, fileId: id} //create an object with file file properties, if you need that
                return resp // return object back to function that called this service
            })
            .catch(e=>console.log(e));
  }

Second function to upload data:

gDriveUploadFile(file, url): Promise<any> { //file and url we got from first func
  let authToken = token
      let headers = new Headers({
        'Authorization': 'Bearer ' + authToken,
        'Content-Type': 'application/json; charset=UTF-8',
        'X-Upload-Content-Type': file.type
      });
      let options = new RequestOptions ({ 
        headers: headers,
      });
      return this.http.post(`${url}`, file, options) //call proper resumable upload endpoint and pass just file as body
          .toPromise()
  }

Maybe solution not ideal, so far I do not handle errors here and do not use resumable features like uploading by chunks, just upload file at once. But hopefully if someone else stuck with GDrive uploading can get an idea.


Post a Comment for "Angular 2+ HTTP POST And GDrive API. Resumable File Upload With Name"