1

I've searched all documents in google drive api and I can't able to find how to upload a file to folderid using REST APi. Can anyone please help me on this?

   public void UploadFiletoDrive()
    {
        var gmodel = GetAccessToken();
        WebRequest request = WebRequest.Create("https://www.googleapis.com/upload/drive/v3/files/?uploadType=media");
        request.Method = "POST";
        request.Headers["Authorization"] = "Bearer " + gmodel.access_token;
        request.ContentType = "image/jpeg";
        Stream dataStream = request.GetRequestStream();
        FileStream filestream = new FileStream(@"C:\Users\Developer\Downloads\unnamed (2).jpg", FileMode.Open, FileAccess.Read);
        byte[] buffer = new byte[4096];
        int bytesRead = 0;
        while ((bytesRead = filestream.Read(buffer, 0, buffer.Length)) != 0)
        {
            dataStream.Write(buffer, 0, bytesRead);
        }
        filestream.Close();
        dataStream.Close();
        WebResponse response = request.GetResponse();
        StreamReader reader = new StreamReader(response.GetResponseStream());
        string responseFromServer = reader.ReadToEnd();
        reader.Close();
        response.Close();
    }
Rajesh
  • 399
  • 6
  • 15

3 Answers3

1

It seems you've missed the Work with Folders docs.

Inserting a file in a folder using Java:

String folderId = "0BwwA4oUTeiV1TGRPeTVjaWRDY1E";
File fileMetadata = new File();
fileMetadata.setName("photo.jpg");
fileMetadata.setParents(Collections.singletonList(folderId));
java.io.File filePath = new java.io.File("files/photo.jpg");
FileContent mediaContent = new FileContent("image/jpeg", filePath);
File file = driveService.files().create(fileMetadata, mediaContent)
        .setFields("id, parents")
        .execute();
System.out.println("File ID: " + file.getId());

Implementation for other languages are also included like PHP, Python, NodeJS.

Also, check this SO thread for additional reference.

body.setParents(Arrays.asList(new ParentReference().setId(folderId)));
Community
  • 1
  • 1
ReyAnthonyRenacia
  • 17,219
  • 5
  • 37
  • 56
  • I've already seen these code in docs, please look at my question once again..am asking using REST APi...not with JAVA or .Net – Rajesh Jul 07 '16 at 06:17
  • please check the code above, am able to insert any file to drive root folder but not to specific folder. – Rajesh Jul 07 '16 at 07:10
1

Your sample code is doing a media upload, ie. no metadata, You should be using a multipart upload so you can specify both metadata such as parent folder id and content.

pinoyyid
  • 21,499
  • 14
  • 64
  • 115
0

Uploading a file to google drive using REST API has following steps.

  • Get parent folderID using list API

  • Create file with parent="folder ID" using create api and get "fileId" in response

  • upload file to "fileId

Following is javascript code to upload file using REST API

const url = 'https://www.googleapis.com/upload/drive/v3/files/' + fileId + '?uploadType=media';
if(self.fetch){
        // console.log("Fetch found, Using fetch");
        var setHeaders = new Headers();
        setHeaders.append('Authorization', 'Bearer ' + authToken.access_token);
        setHeaders.append('Content-Type', mime);
        var setOptions = {
        method: 'PATCH',
        headers: setHeaders,
        body: blob
        };
        fetch(url,setOptions)
        .then(response => { if(response.ok){
            // console.log("save to google using fetch");
        }
                    else{
                    // console.log("Response wast not ok");
                    }
                  })
        .catch(error => {
        // console.log("There is an error " + error.message);
        });
        }
s007
  • 728
  • 6
  • 12