redditor
redditor

Reputation: 4286

Get external URL and save to Drive

I want to take a PDF URL and save it to Drive. The folder ID and URL are correct.

function uploadDoc(){
  var folder = DriveApp.getFolderById('my_folder_id');
  var url = 'my_url';

  var blob = UrlFetchApp.fetch(url);
  var blob2 = blob.getAs('appl‌​ication/pdf');

  var newFile = folder.createFile('filename.pdf',blob2);
}

When I run this, I get:

Exception: Converting from binary/octet-stream to appl‌​ication/pdf is not supported.

Upvotes: 0

Views: 525

Answers (1)

ADW
ADW

Reputation: 4247

You'll need to fix two things:

  1. After UrlFetchApp.fetch(url) you need to use the getBlob() method. The getAs('appl‌​ication/pdf') method is not strictly required.

  2. If you are using a blob, then you need to use the createFile(blob) method.

You are using the createFile(name, content) method and in this method, content is string not blob.

Then to name of the new file, you'll need the setName(name) method.

function uploadDoc() {
  var url = 'https://www.gstatic.com/covid19/mobility/2021-02-21_AF_Mobility_Report_en.pdf';
  var foID = 'my_folder_id';
  var folder = DriveApp.getFolderById(foID);
  var blob = UrlFetchApp.fetch(url).getBlob();
  var newFile = folder.createFile(blob).setName('filename.pdf');
}

Upvotes: 2

Related Questions