0

I was able to upload an image file to google drive (Service Account) using google drive API. In return of the post, I got a filId from google.

Uploaded file to drive

I then used this fileId to create public read-only permission on the file.

added permission to file

But how do I get the public URL for the file? (I am using V3 of drive API)

I tried using "webContentLink":"https://drive.google.com/uc?id={FileID}&export=download" but the downloaded file is corrupted and not opening.

I also tried using "alternateLink": "https://drive.google.com/file/d/{FileId}/view?usp=drivesdk" but this also not working.

trying to view alternateLink

Here is my method to upload file to drive:

public static String uploadFile(String accesstoken,String FolderId, blob file, String filetype, String filename){
    String thumbnailLink;
    String fid;
    String clink;
    try{
        if(String.isBlank(accesstoken) || file.size()==0 || String.isBlank(filetype) || String.isBlank(filename)){
            throw new applicationException('One or more required parameters are not passed!');
        }
    }catch(applicationException e){
        System.debug(LoggingLevel.ERROR,'Call exception ' + e.getMessage());
    }
    String boundary = '----------9889464542212';
    String delimiter = '\r\n--' + boundary + '\r\n';
    String close_delim = '\r\n--' + boundary + '--';
    String bodyEncoded = EncodingUtil.base64Encode(file);
    String body = '';
    if(FolderId !=''){
        body = delimiter + 'Content-Type: application/json; charset=UTF-8\r\n\r\n' + '{ "name" : "' + filename + '",' + ' "mimeType" : "' + filetype + '",' + '"parents":[{"id":"'+ FolderId +'"}]}' + delimiter + 'Content-Type: ' + filetype + '\r\n' + '\r\n' + bodyEncoded + close_delim;
    }
    else{            
        body = delimiter + 'Content-Type: application/json; charset=UTF-8\r\n\r\n' + '{ "name" : "' + filename + '",' + ' "mimeType" : "' + filetype + '"}'+ delimiter + 'Content-Type: ' + filetype + '\r\n' + '\r\n' + bodyEncoded + close_delim;
    }

    System.debug('Body: '+body);

    try{
        Http http = new Http();
        HttpRequest req = new HttpRequest();
        req.setEndpoint('https://www.googleapis.com/upload/drive/v3/files?uploadType=multipart&withLink=true');
        req.setHeader('Authorization', 'Bearer ' + accesstoken);
        req.setHeader('Content-Type', 'multipart/related; boundary="' + boundary + '"');
        req.setHeader('Content-length', String.valueOf(body.length()));
        req.setBody(body);
        req.setMethod('POST');
        req.setTimeout(60 * 1000);
        HttpResponse resp = http.send(req);
        System.debug(resp.getBody());

        system.debug('Test');
        Map<String, Object> p = (Map<String, Object>) JSON.deserializeUntyped(resp.getBody());
        thumbnailLink= (String) p.get('thumbnailLink');
        fid=(String) p.get('id');
        System.debug('File Id: '+fid);
        clink='https://drive.google.com/uc?export=view&id='+fid;
        System.debug('clink: '+clink);
    } catch
        (Exception e) {
            System.debug(LoggingLevel.ERROR,
                         'Call exception ' + e.getMessage());
        }
    String body1 = '{"role":"reader","type":"anyone"}';
    try{
        //Changing file permission to public viewable using link
        Http http = new Http();
        HttpRequest req1 = new HttpRequest();
        req1.setEndpoint('https://www.googleapis.com/drive/v2/files/'+fid+'/permissions');
        req1.setHeader('Authorization', 'Bearer ' + accesstoken);
        req1.setHeader('Content-Type', 'application/json');
        req1.setHeader('Content-length', String.valueOf(body1.length()));
        req1.setBody(body1);
        req1.setMethod('POST');
        req1.setTimeout(60 * 1000);
        HttpResponse resp1 = http.send(req1);
        System.debug(resp1.getBody());
    } catch
        (Exception e) {
            System.debug(LoggingLevel.ERROR,
                         'Call exception ' + e.getMessage());
        }
    return fid;

}
  • Hello! Can you see the file correctly in your Drive? What is the `mimeType`? – Jescanellas May 13 '20 at 07:41
  • Hey! Its a Service account and hence I can't visually inspect the file in the drive but I was able to query the binary content of the file back and verify it. Also "mimeType": "image/jpeg". – Priyank Saklani May 13 '20 at 08:30
  • I see, can you try to do the same with a regular user Drive account? If it fails, try to upload the file manually using the UI and see if the download is corrupted too. – Jescanellas May 13 '20 at 11:14
  • #UPDATE 1: All drives have a default pdf named "Getting started". I was able to add "public, read-only" permission to that file and view the file using the 'alternate link' of the file. This suggest there is something wrong with the upload method. Could someone help me out? – Priyank Saklani May 18 '20 at 11:53
  • #UPDATE 2: After some trial and error I was able to share the file uploaded to my Service Account with my normal Google account. Now I can see the file under the "Shared With Me" section of my normal drive. – Priyank Saklani May 27 '20 at 13:42
  • Link to file: https://drive.google.com/file/d/1PyczJatbZ7IvB4faHts-J4FN_wqAMweb/view?usp=sharing – Priyank Saklani May 27 '20 at 13:49

0 Answers0