1

First thank you in advance for any replies/solutions.

Disclaimer: This solution IS NOT USED FOR HOSTING IMAGES, it's for an internal process that for 100 reasons won't follow a redirect to GET the image.

This question is: How can one use Google App Script (or Drive API) to collect the final redirected URL from a link to a google drive file (in this case a image.jpg) for pasting into a google sheet. Anyone reading this can assume that the image is shared publicly for this example.

Workflow: The script pulls an image file from an external URL:

var image = UrlFetchApp.fetch(imageUrl).getBlob();

The script then renames the image and then places it into a google drive folder using the Drive API:

name = String(name).toLowerCase().replace(/\s+/g, '').replace(/[^\w\s]/gi, ''); //removes all spaces, sets the name lower case and then removes all extra characters
      image.setName(name);


// This would convert the file to mime type image/jpeg but it doesn't work on some gif's or jpeg 200~c

      var contentType = image.getContentType();

     try{

        if (contentType != "image/jpeg"){
          image = image.getAs('image/jpeg');
        }

      } catch (err){
        Logger.log("Didn't work");
      }

  } 
    } else {
      return imageUrl;
      }

    if (contentType === "image/jpeg"){
        var file = {
          title: name +'.jpg',
          mimeType: 'image/jpg',
          "parents": [{
          "kind": "drive#fileLink",
          "id": "folderID" //imageFolderID
           }] 
         };



        file = Drive.Files.insert(file, image);
        var driveId = file.id ; 

Then it pastes the publicly shared link (string) for that file into a sheet for later retrieval by another program. The issue is that the link the code below produces leads to a redirect.

So the real question is: How do I grab the final URL that this link is being redirected to? (Hint: It's not in the request or response below so I can't parse it out of those)

An examples of the links in question:

Pre Redirect: https://googledrive.com/host/0B5gf6NnVG8VQflQwZHBMZVJiNFhlbkpEWUY3OHZnWS02ZjBZa2NBQUVCWWljVWpVWm5zcTQ/abc1.jpg

Post Redirect: https://050dfacf921e33f0950333e36cbaf7c8256bd042.googledrive.com/secure/AOjc2GPc7PRSJAfYLixwxgly6DSeHpDWD0XeuJDkW42pIe5YgjTBlwZ_MUeB-nKlYS-amWukCgcqtac4sKQs-D3ah4EFK7rPUHVwmNr0jh6EZ_1mwDfzgrToK1gUPxRUef_YKPZ4UWLYzMZYogQxuF-KwaDJsGgM5VUeQvyBDP2bfRKjCxoEMxrkewzi-Zwgp3dYgRxfWMxggLWP4Wmfadl3zJ4sD7erqU0n1yPFo8obxZt7MCx-V_PFJaG5XX0TFw6u3UehmB0oJNrSODRfbj8eh8ncNCGCkaGJ7etODSpb8fAXXULu9FAh9sc9likOEy3jezVil3xRpw0_dr3b_TXS_nBEwhFV1N7uwFONsSIRa0lThz2P4-XJnhiegtq95VCdrVDiQwFOBYgro6vEZSPefzz9PGQ-bkhwiNq7PA_7e2xCIdaMOIyoriphCdbW6FyUox405Tu60Pec9NB6pGUv78vi0Znrh5s8MJYhBInkP5CoN3obhc4qu5QrR3bro4ArtYm34A3vdg3rMhStFlatD8q4g7BOuL6iraOndgIPBHXQdwEtMqNwLhpLI59iefyRZzdNBTxm2Ly1ZInj4-EYKl4h5ajKoA==/host/0B5gf6NnVG8VQflQwZHBMZVJiNFhlbkpEWUY3OHZnWS02ZjBZa2NBQUVCWWljVWpVWm5zcTQ/abc1.jpg

My first attempt:

var sharedUrl = 'https://googledrive.com/host/'+ folderId + "/" + driveName;
var response = UrlFetchApp.fetch(sharedUrl);
var request = UrlFetchApp.getRequest(cleanUrl);
Logger.log(response.getContentText()); //doesn't contain the final link
Logger.log(request); //neither do I
Logger.log(response); //nope

Second Attempt: I have tried to work it out using traditional JS (.location) but that is not working. (Yes the code below makes 0 sense at this point but my multiple iterations aren't working either:

//        Logger.log("Page location is " + cleanUrl.location.href);

3rd Attempt: I found this Stack Link How to detect a redirected URL?

But I am unable to work this correctly:

try {
    HttpResponse response = client.execute(getRequest);
    final int statusCode = response.getStatusLine().getStatusCode();
    if(statusCode == HttpStatus.SC_MOVED_PERMANENTLY || statusCode == HttpStatus.SC_MOVED_TEMPORARILY){
        String location = response.getHeaders("Location")[0].toString();
        String redirecturl = location.replace("Location: ", "");
    }
}

Any encouragement, help or just general banter would be appreciated, and thanks to anyone who is willing to throw in their two cents!

1 Answer 1

0

By Default Google Apps Script followredirects is true so you won't find Location header. so you need to set it as false as below.

var url ='https://googledrive.com/host/' + file.id;
var options = {"method" : "GET","followRedirects" : false};
var redirecturl = UrlFetchApp.fetch(url, options).getAllHeaders().Location;
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.