2013-09-17 4 views
3

Я пытаюсь програмотно вставить изображение в документ. Я могу заставить это работать отлично с изображением с URL-адресом, таким как http://www.geeks-on-wheels.net/wp-content/uploads/apple.jpg. Проблема возникает при попытке использовать образ, расположенный на моем Google Диске. URL-адрес выглядит так: https://docs.google.com/a/finance-in-motion.com/file/d/0B5sPSMZ9pf-QMG9GOVROakxQYmM/edit или https://docs.google.com/a/finance-in-motion.com/file/d/0B5sPSMZ9pf-QMG9GOVROakxQYmM/edit?usp=sharing. Скрипт, похоже, не знает, что с ним делать, и выдает ошибку. Любая помощь будет оценена по достоинству.Вставка образа Google Диска в документ с использованием скрипта Google Apps

С уважением,

Шон

ответ

8

Для вставки файлов с Диска не использовать HTTP маршрут, если файл не был обнародован через drive hosting

Вставить использовать встроенные в APIs читать блог файла и вставьте img.

Вот пример вставки jpg с моего диска (или файла, к которому у меня есть доступ) к документу.

function insertImageFromDrive(){ 
var fileId = '0B_dyIOzoasdfasdfPVTMxdTVXWDg'; 
var img = DriveApp.getFileById(fileId).getBlob(); 
DocumentApp.getActiveDocument().getBody().insertImage(0, img); 
} 

Это будет изображение в верхней части документа. Чтобы получить больше контроля над заменой курсора/выбора, см. this blog post.

+0

Отличный ответ! Это очистило путаницу. Еще раз спасибо! – user1682683

+0

Как получить идентификатор файла? Он не отображается в информационной панели. – mrplants

1

У меня есть задача, где я должен сделать форму для загрузки своих данных и изображений в электронную таблицу google. Поэтому я создал три файла для выполнения этой задачи в своем проекте Google App Script.

Файлы: Code.gs (несущий код форма обращения)

form.html (переноска формы HTML-код)

thanks.html (шоу После успешного представления формы)

и на моем диске Google у меня есть папка с именем «uploads», где все изображения, загружаемые из формы и ее ссылки, сохраняются в электронной таблице вместе с другими данными формы. вы можете проверить работает приложение здесь: https://script.google.com/macros/s/AKfycbwmUDXR54cWO8PbCaexqDDo2397kyAi-AluUwWuhfG0VqTyK5ed/exec данные и сохранит в этом spreasheet: https://docs.google.com/spreadsheets/d/12StuWSCebwRBBTxOcYEr8ksHN8PJhtDIE7NWi9UwGf0/edit#gid=0

Ниже перечислены файлы кода

Code.gs

var submissionSSKey = [YOUR-SPREADSHEET-ID]; 
var folderId = [YOUR-FOLDER-ID]; 

function doGet(e) { 
    var template = HtmlService.createTemplateFromFile('form.html'); 
    template.action = ScriptApp.getService().getUrl(); 
    return template.evaluate(); 
} 


function processForm(theForm) { 
var fileBlob = theForm.myFile; 
var folder = DriveApp.getFolderById(folderId); 
var doc = folder.createFile(fileBlob); 


// Fill in response template 
var template = HtmlService.createTemplateFromFile('thanks.html'); 
var fname = template.name = theForm.name+','+fileBlob.total; 
var guests = template.guests = theForm.guests; 
var filters = template.filters = theForm.filters_value; 
var email = template.email = theForm.email; 

var fileUrl = template.fileUrl = doc.getUrl(); 
var phone = template.phone = theForm.phone; 
var bedroom = template.bedroom = theForm.bedroom; 
var beds = template.beds = theForm.beds; 
var bathroom = template.bathroom = theForm.bathroom; 
var property_name = template.property_name = theForm.property_name; 
var property_description = template.property_description = theForm.property_description; 
var address = template.address = theForm.address; 

// Record submission in spreadsheet 
var sheet = SpreadsheetApp.openById(submissionSSKey).getSheets()[0]; 
var lastRow = sheet.getLastRow(); 
var targetRange = sheet.getRange(lastRow+1, 1, 1, 12).setValues([[fname,guests,filters,email,fileUrl,phone,bedroom,beds,bathroom,property_name,property_description,address]]); 


// Return HTML text for display in page. 
    return template.evaluate().getContent(); 
} 

form.html

<!DOCTYPE html> 
<html> 
    <head> 
    <base target="_top"> 
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script> 
    <script> 
    $(document).ready(function(){ 
    document.getElementById("myForm").reset(); 
    $('input[id=filtercheck]').change(function(){ 
       var allVals = []; 
      $('input[type="checkbox"]:checked').each(function() { 
       //  removed the space^
       allVals.push($(this).val()); 
      }); 
      $('#filters_value').val(allVals); 
    }); 
    }); 


function mySubmitFunction() 
{ 
    if(!$('input[id=terms_check]').is(':checked')) 
    { 
    return false; 
    } 
} 

// Javascript function called by "submit" button handler, 
// to show results. 

function updateOutput(resultHtml) { 
    toggle_visibility('inProgress'); 
    var outputDiv = document.getElementById('output'); 
    outputDiv.innerHTML = resultHtml; 
} 

// From blog.movalog.com/a/javascript-toggle-visibility/ 
function toggle_visibility(id) { 
var e = document.getElementById(id); 
if(e.style.display == 'block') 
    e.style.display = 'none'; 
else 
    e.style.display = 'block'; 
} 

</script> 
<style> 
#formDiv{width:90%; padding:10px; font-size:12px;} 
/*.singlerow{width:100%; height:auto; float:left; margin-top:10px;}*/ 
input[type=text], input[type=email], select {min-width:200px; height:30px; margin:10px; } 
.top_bar{width:100%; height:40px; float:left; background-color:#000000; padding:5px;} 
.top_bar img{margin-top:5px; float:left;} 
</style> 
</head> 
<body> 

<div class="top_bar"><a href="http://www.nzholidayhomes.nz"><img src="http://dx577khz83dc.cloudfront.net/4085/c5b11516-3be0-4e08-b962-b2e761e895cf.png" height="30" /></a></div> 
<div id="formDiv"> 
<!-- Form div will be hidden after form submission --> 
<form id="myForm" onsubmit="return mySubmitFunction()" style="display:block;"> 

<input name="name" type="text" placeholder="Name" /> 
<input name="phone" type="text" placeholder="phone" /> 
<input name="email" type="text" placeholder="Email" /><br> 



<select name="guests"> 
<option>Select Guests</option> 
<option>1</option> 
<option>2</option> 
<option>3</option> 
</select> 

<select name="bedroom"> 
<option>Select Bedroom</option> 
<option>1</option> 
<option>2</option> 
<option>3</option> 

</select> 


<select name="beds"> 
<option>Select Beds</option> 
<option>1</option> 
<option>2</option> 
<option>3</option> 

</select> 

<select name="bathroom"> 
<option>Select Bathroom</option> 
<option>1</option> 
<option>2</option> 
<option>3</option> 

</select><br> 


<input type="text" name="property_name" Placeholder="Property Name" /> 
<input type="text" name="property_description" placeholder="Property Description"/> 
<input type="text" name="address" placeholder="Address"/><br> 





<input type="checkbox" value="Suitable for Children" name="filtercheck" id="filtercheck"> <label>Suitable for Children</label> 
<input type="checkbox" value="Suitable for Events" name="filtercheck" id="filtercheck"><label> Suitable for Events</label> 
<input type="checkbox" value="Suitable for Pets" name="filtercheck" id="filtercheck"><label> Suitable for Pets</label> 
<input type="checkbox" value="Suitable for Smoking" name="filtercheck" id="filtercheck"><label> Suitable for Smoking</label><br> 



<input type="checkbox" value="Stove" name="filtercheck" id="filtercheck"><label> Stove</label> 
<input type="checkbox" value="Microwave" name="filtercheck" id="filtercheck"> Microwave 
<input type="checkbox" value="Dishwasher" name="filtercheck" id="filtercheck"> Dishwasher 
<input type="checkbox" value="Fridge" name="filtercheck" id="filtercheck"> Fridge 
<input type="checkbox" value="Freezer" name="filtercheck" id="filtercheck"> Freezer<br> 



<input type="checkbox" value="Washer" name="filtercheck" id="filtercheck"> Washer 
<input type="checkbox" value="Dryer" name="filtercheck" id="filtercheck"> Dryer 
<input type="checkbox" value="Fire Alarm" name="filtercheck" id="filtercheck"> Fire Alarm 
<input type="checkbox" value="First Aid Kit" name="filtercheck" id="filtercheck"> First Aid Kit 
<input type="checkbox" value="Fire Extinguisher" name="filtercheck" id="filtercheck"> Fire Extinguisher<br> 


<input type="checkbox" value="TV" name="filtercheck" id="filtercheck"> TV 
<input type="checkbox" value="Sky" name="filtercheck" id="filtercheck"> Sky 
<input type="checkbox" value="Wifi" name="filtercheck" id="filtercheck"> Wifi 
<input type="checkbox" value="Fireplace" name="filtercheck" id="filtercheck"> Fireplace 
<input type="checkbox" value="Heaters" name="filtercheck" id="filtercheck"> Heaters<br> 


<input type="checkbox" value="Spa" name="filtercheck" id="filtercheck"> Spa 
<input type="checkbox" value="Pool" name="filtercheck" id="filtercheck"> Pool 
<input type="checkbox" value="BBQ" name="filtercheck" id="filtercheck"> BBQ 
<input type="checkbox" value="Off-street Parking" name="filtercheck" id="filtercheck"> Off-street Parking 
<input type="checkbox" value="On-street Parking" name="filtercheck" id="filtercheck"> On-street Parking<br> 
<input type="hidden" value="" id="filters_value" name="filters_value" /> 

Image Files Only: <input name="myFile" type="file" multiple /><br> 


<input type="checkbox" id="terms_check" /> Agree to the <a href="#">Terms &amp; Conditions</a><br><br><br> 


<input type="button" id="form_btn_submit" value="Submit" onclick="toggle_visibility('myForm'); 
    toggle_visibility('inProgress'); 
    google.script.run.withSuccessHandler(updateOutput).processForm(this.parentNode);" /> 

</form> 

<div id="inProgress" style="display: none;"> 
<!-- Progress starts hidden, but will be shown after form submission. --> 
Your Data is uploaded. Please check the <a href="https://docs.google.com/spreadsheets/d/12StuWSCebwRBBTxOcYEr8ksHN8PJhtDIE7NWi9UwGf0/edit?pli=1#gid=0&vpid=A2" target="_blank">spreadsheet</a> 
</div> 

<div id="output"> 
    <!-- Blank div will be filled with "Thanks.html" after form submission. --> 
</div> 


</div> 

<a href="http://www.nzholidayhomes.nz">Click here to back to main website</a> 

</body> 
</html> 

thanks.html

<!DOCTYPE html> 
<html> 
<head> 
<base target="_top"> 
</head> 
<body> 
<div> 
<h1>Thanks</h1> 
<p>Thank you for your submission.</p> 
Name: <?= fname ?><br/> 
Filters: <?= filters ?><br/> 

Email: <?= email ?><br/> 
File URL: <?= fileUrl ?><br/> 
</div> 
</body> 
</html> 
Смежные вопросы