Reputation: 2714
I need the absolute google drive api link as result from my script but I don’t know how.
This is my script:
I have a html form and Im uploading a media file to google drive and return the file. This is my code:
<form id="form">
<input name="file" id="uploadfile" type="file">
<input name="filename" id="filename" type="text">
<input id="submit" type="submit">
</form>
<script>
const form = document.getElementById('form');
form.addEventListener('submit', e => {
e.preventDefault();
const file = form.file.files[0];
const fr = new FileReader();
fr.readAsArrayBuffer(file);
fr.onload = f => {
const url = "https://script.google.com/macros/s/###/exec"; // <--- Please set the URL of Web Apps.
const qs = new URLSearchParams({filename: form.filename.value || file.name, mimeType: file.type});
fetch(`${url}?${qs}`, {method: "POST", body: JSON.stringify([...new Int8Array(f.target.result)])})
.then(res => res.json())
.then(e => console.log("https://drive.google.com/uc?export=download&id=" + e.fileId))
.catch(err => console.log(err));
}
});
</script>
This is my server script
function doPost(e) {
const folderId = "root"; // Folder ID which is used for putting the file, if you need.
const blob = Utilities.newBlob(JSON.parse(e.postData.contents), e.parameter.mimeType, e.parameter.filename);
const file = DriveApp.getFolderById(folderId || "root").createFile(blob);
const responseObj = {filename: file.getName(), fileId: file.getId(), fileUrl: file.getUrl()};
return ContentService.createTextOutput(JSON.stringify(responseObj)).setMimeType(ContentService.MimeType.JSON);
}
One stackoverflow User described how to get the link I need. How to put this steps in the script?
Get the file ID from the sharing link https://drive.google.com/file/d/your_file_id/view?usp=sharing
Construct the direct link http://docs.google.com/uc?export=open&id=your_file_id
Paste the direct link into a web browser and hit enter
Copy the resulting URL after you have been redirected by your browser Note: This will be a much longer URL that looks something like this: https://doc-XX-XX-docs.googleusercontent.com/docs/securesc/XXXXXXXXXXXXXXXXXXXXX/XXXXXXXXXXXXXXXXXXXX/000000000000000/0000000000000000000000/*/your_file_id?e=open
Using this final URL is the only way I could get my uploaded sound files to work with Actions on Google.
Upvotes: 1
Views: 946
Reputation: 50761
After getting the fileUrl, use Urlfetch
to fetch the resource. If it is redirected, you'll get status code 302
with the redirected url in Location
header. Authorization can be handled with ScriptApp.getOAuthToken()
, if needed.
const url = `https://docs.google.com/uc?export=open&id=${file.getId()}`;
const response = UrlFetchApp.fetch(url,{
headers: {
Authorization: `Bearer ${ScriptApp.getOAuthToken()}`
},
followRedirects: false
});
const statusCode = response.getStatusCode();
if (String(statusCode)[0] === "3") console.log(response.getAllHeaders()['Location'])
else console.log("No redirect")
Upvotes: 1