user2916405
user2916405

Reputation: 147

app script file upload return file url to Html page

I've modified this script to upLoad a file to a folder in my google drive. But I also need it to return the url link of that uploaded file back into to a span or a form field.

I can't get it to return the url link.

So far I this is what my code looks like.

    <!DOCTYPE html>
    <html>
     <head>
   <base target="_top">
    </head>
   <body>

 <form>
 <label>INCLUIR IMAGEM</label><input type="file" accept="image/*" capture="camera" name="imageFile"/>

   <!-- <input type="file" name="imageFile">-->
  <input type="button" value="Upload File" 
    onclick="google.script.run.withSuccessHandler(updateUrl).upload(this.parentNode)">
     </form><br/><br/>
         <div id="output"></div>
          </body>
          </html>




<script>
  function updateUrl(imageUrl) {
  var div = document.getElementById('output');
  div.innerHTML = '<span>' + imageUrl +'</span>';
  }
  </script>

code.gs

function upload(e) { 
 // Folder ID of destination folder
 var destination_id = '1qghuk1-kShw8NMJLhzmRGJJwM-dHVJ5t';
 var contentType = 'image/jpeg'; 
 var imageUrl = e.imageFile;
 var destination = DriveApp.getFolderById(destination_id);
 destination.createFile(imageUrl);
 var folder = destination.next();
 var files = folder.getFiles(); 
if (files.hasNext()) {
  // For this test, use first found file
  var file = files.next();
  var imageUrl = Drive.Files.get(file.getId()).webContentLink;


Logger.log(imageUrl);
return imageUrl;  


 }

 }

Upvotes: 1

Views: 1276

Answers (1)

Tanaike
Tanaike

Reputation: 201428

  • You want to retrieve webContentLink of the uploaded file.

If my understanding is correct, how about this modification? I think that the script of your HTML side is correct.

From:

destination.createFile(imageUrl);
var folder = destination.next();

var files = folder.getFiles(); 
if (files.hasNext()) {
  // For this test, use first found file
  var file = files.next();
  var imageUrl = Drive.Files.get(file.getId()).webContentLink;


Logger.log(imageUrl);
return imageUrl;  


 }

To:

var file = destination.createFile(imageUrl);
var imageUrl = Drive.Files.get(file.getId()).webContentLink;
Logger.log(imageUrl);
return imageUrl;

or, if you are not required to use Drive API, how about the following modification?

To:

var file = destination.createFile(imageUrl);
return "https://drive.google.com/uc?export=download&id=" + file.getId();

Reference:

If I misunderstood your question and this was not the direction you want, I apologize.

Upvotes: 2

Related Questions