Seems like this should be easier. But admittedly I don't understand blobs.
function doGet(e) {
var app = UiApp.createApplication();
var panel = app.createVerticalPanel().setId('panel');
var fileUpload = app.createFileUpload().setName('theFile').setId('theFile');
var handler = app.createServerChangeHandler('uploadfile');
handler.addCallbackElement(panel);
fileUpload.addChangeHandler(handler);
panel.add(fileUpload);
app.add(panel);
return app;
}
function uploadfile(e)
{
// data returned which can be used to create a blob
// assuming mime-type to be a text file in this example
var fileBlob = Utilities.newBlob(e.parameter.thefile, "text/plain","file.txt" );
// Create a new file
var doc = DocumentApp.create('Uploaded Text File');
doc.appendParagraph(fileBlob.getDataAsString());
// Save and close the document
doc.saveAndClose();
//var doc = DocsList.createFile(fileBlob.getDataAsString());
var app = UiApp.getActiveApplication();
app.getElementById('panel').add(app.createLabel('File Uploaded successfully'));
return app;
}
I keep getting undefined returned when I attempt to upload a file using this Google Apps Script Code. All I want to do is upload a text file to my Google Drive.
What should I do to fix this code? or is there a better way to do this?
Google Apps Script now has "Experimental" Resources to Advanced Google Services. I counted 15 Advanced Services, including Drive API.
Click the Resources menu:
You must also go to the Google Developers console, and enable Drive Service there also.
The Google Documentation is at: Advanced Drive Services
Here is some sample code from Google:
function uploadFile() {
var image = UrlFetchApp.fetch('http://goo.gl/nd7zjB').getBlob();
var file = {
title: 'google_logo.png',
mimeType: 'image/png'
};
file = Drive.Files.insert(file, image);
Logger.log('ID: %s, File size (bytes): %s', file.id, file.fileSize);
}
EDIT
I thought there was no way to upload a file from the users computer to Google drive using the HTML Service, but luckily I'm wrong again! :)
File Upload with HTML Service
To do a file upload, you cannot use a server handler. You must use a FormPanel and a Submit button. See the FileUpload widget's documentation.
Related
i'm trying to write string to text file then upload to google drive
is it possible via javascript or using react-google-picker ?
here's my code to download file to my local storage...
Download= () => {
var _this = this;
const element = document.createElement("a");
const file = new Blob([_this.state.xmldata], { type: 'text/plain' });
element.href = URL.createObjectURL(file);
element.download = "text.txt";
document.body.appendChild(element);
element.click();
}
Thank you
I believe what you're looking for is if google drive has an api that enables you to create a file. This isn't really react specific.
https://gist.github.com/tanaikech/bd53b366aedef70e35a35f449c51eced
User uploaded file to google drive via javascript?
https://developers.google.com/drive/api/v3/reference/files/create
I believe you'll find the 3rd link to be the most useful. Essentially, you just need to post the file to their rest api with your authentication:
POST https://www.googleapis.com/upload/drive/v3/files
Here is the full API Documentation: https://developers.google.com/drive/api/v3/reference/
As per the Chrome version >=60 the PDF view functionality by any top-frame navigations options like
<A HREF=”data:…”>
window.open(“data:…”)
window.location = “data:…”
has been blocked by Google for which the discussion can be found at Google Groups. Now the problem is how to display the PDF on web without explicitly or forcibly making PDF to download. My old code looked as below via window.open to view the PDF data
dataFactory.getPDFData(id, authToken)
.then(function(res) {
window.open("data:application/pdf," + escape(res.data));
},function(error){
//Some Code
}).finally(function(){
//Some Code
});
In above I extract the PDF data from server and display it. But since window.open is blocked by Chrome and as suggested by one of the expert over here to use <iframe> to open the PDF data and I tried but it's not working. It always says Failed to Load PDF Data as below
The updated JS code for the <iframe> looks as below:
dataFactory.getPDFData(id, authToken)
.then(function(res) {
$scope.pdfData = res.data;
},function(error){
//Some Code
}).finally(function(){
//Some Code
});
And the HTML looks as below:
<iframe src="data:application/pdf;base64,pdfData" height="100%" width="100%"></iframe>
How can I proceed and bring back the original PDF view functionality? I searched over other stack questions but out of luck on how to resolve this. May be I did something wrong or missed something with the iframe code but it's not working out.
After unable to find the desired result I came up with below approach to resolve the issue.
Instead of opening the PDF on new page what I did is as soon as user clicks on the Print button PDF file gets downloaded automatically. Below is the source for same.
//File Name
var fileName = "Some File Name Here";
var binaryData = [];
binaryData.push(serverResponse.data); //Normal pdf binary data won't work so needs to push under an array
//To convert the PDF binary data to file so that it gets downloaded
var file = window.URL.createObjectURL(new Blob(binaryData, {type: "application/pdf"}));
var fileURL = document.createElement("fileURL");
fileURL.href = file;
fileURL.download = serverResponse.name || fileName;
document.body.appendChild(fileURL);
fileURL.click();
//To remove the inserted element
window.onfocus = function () {
document.body.removeChild(fileURL)
}
In your old code :
"data:application/pdf," + escape(res.data)
In the new :
your iframe src is like "data:application/pdf;base64,pdfData"
Try to remove base64 from the src, it seems to be already present in the value of 'pdfdata'.
I've just started to use GAS and I'm having issues with uploading files to a GDrive folder.
I'm using this way to read the form (html+bootstrap) file inputs and generate the files into a drive folder. There are 4 file inputs for different topics on the form.
function processForm(theForm) {
//Variables from files to upload
var talleres = theForm.talleres;
var sistEval = theForm.sistEval;
var otrosDoc = theForm.otrosDoc;
var matsDigi = theForm.matsDigi;
var folder = DriveApp.getFolderById(folderId);
var nombTuto = theForm.curso+'_'+theForm.nombre+'_'+theForm.paterno+'_'+theForm.materno;
var foldTuto = DriveApp.createFolder(nombTuto);
var doc = foldTuto.createFile(talleres);
var doc2 = foldTuto.createFile(sistEval);
var doc3 = foldTuto.createFile(otrosDoc);
var doc4 = foldTuto.createFile(matsDigi);
folder.addFolder(foldTuto);
DriveApp.removeFolder(foldTuto);
I've limited the file size with a js validation on the form.html to 100Mb each file, but when I try to upload more than 50Mb in total (considering the 4 files) the console of bugzilla returns the message:
NetworkError: Connection failure due to HTTP 500
And the web gets frozen, and obviously didn't save anything.
So, I need to know if i have to change the method for upload because I'm searching on the documentation of GAS page but can't find anything about "upload Quotas" or detailed information from the error 500, just like "Internal Server Error".
Sorry about my english, regards.
With the Drive Service of Google Apps Script the limit is set to 10MB per upload. I guess that the Blob function has the same limits that the others, it's an oversight from Google.
Throws an exception if content is larger than 10MB.
Issue already reported here: #552, #2806
I guess this limitation is due to the limitation of URL Fetch POST size.
I am developing a custom application in "ServiceNow" which requires Javascript and HTML coding. So, I have a field say, "description" on my form. How may I save this field's value to a word document on the desktop?
While JavaScript cannot create a file for you to download by itself, ServiceNow does have a way for you to create one. Creating a Word document is impossible without the use of a MID server and some custom Java code, but if any file type will do you can create an Excel file using an export URL. To test this out, I made a UI Action in a developer instance running Helsinki on the Problem table. I made a list view that contains only the field that I wanted to save, and then used the following code in the UI action:
function startDownload() {
window.open("https://dev13274.service-now.com/problem_list.do?EXCEL&sysparm_query=sys_id%3D" +
g_form.getUniqueValue() + "&sysparm_first_row=1&sysparm_view=download");
}
When the UI action is used, it opens a new tab that will close almost immediately and prompt the user to save or open an Excel file that contains the contents of that single field.
If you want to know more about the different ways you can export data from ServiceNow, check their wiki-page on the subject.
You can use the HTML5 FileSystem API to achieve that
window.requestFileSystem(window.PERSISTENT, 1024*1024, function (fs) {
fs.root.getFile('file.txt', {create: true}, function(fileEntry) {
fileEntry.createWriter(function(fileWriter) {
var blob = new Blob([description.value], {type: 'text/plain'});
fileWriter.write(blob);
});
});
});
FYI, chrome supports webkitRequestFileSystem.
Alternatively, use a Blob and generate download link
var text = document.getElementById("description").value;
var blob = new Blob([text], {type:'text/plain'});
var fileName = "test.txt";
var downloadLink = document.createElement("a");
downloadLink.download = fileName;
downloadLink.href = window.webkitURL.createObjectURL(textFile);
downloadLink.click();
Javascript protects clients against malicious servers who would want to read files on their computer. For that reason, you cannot read or write a file to the client's computer with javascript UNLESS you use some kind of file upload control that implicitely asks for the user's permission.
Ive read a lot about the filesystem API and HTML5, but i just couldn't find a working solution so i ask you guys:
I want to have a file upload form, drag drop or regular input box doesnt matter, however i want to select a file, and after uploading it should take the file or a whole folder and "upload" it to the filesystem located on the clients computer. The upload is in brackets because i actually want to copy the file/folder to the clients local file system.
Is it even possible? Because i want to make an application, where a user can upload his files such as music or large videos and movies to his local filesystem and edit/watch etc them in my application. I know i have to upload those big files i have to cut them into pieces and load them stacked up, but i just want to start little :)
Thanks in advance
There's indeed little information on this subject at the moment, so I put together an example that combines:
Using the webkitdirectory attribute on <input type="file">.
This allows the user to select a directory using an appropriate dialog box.
Using the Filesystem API.
This is about the sandboxed filesystem which allows you to store files on the client's machine.
Using the File API.
This is the API that allows you to read files. The files are accessible through an <input type="file"> element, through a transfer using drag and drop, or through the Filesystem API.
As these are currently only working nicely in Chrome, I used the webkit prefix where necessary.
http://jsfiddle.net/zLna6/3/
The code itself has comments which I hope are clear:
var fs,
err = function(e) {
throw e;
};
// request the sandboxed filesystem
webkitRequestFileSystem(
window.TEMPORARY,
5 * 1024 * 1024,
function(_fs) {
fs = _fs;
},
err
);
// when a directory is selected
$(":file").on("change", function() {
$("ul").empty();
// the selected files
var files = this.files;
if(!files) return;
// this function copies the file into the sandboxed filesystem
function save(i) {
var file = files[i];
var text = file ? file.name : "Done!";
// show the filename in the list
$("<li>").text(text).appendTo("ul");
if(!file) return;
// create a sandboxed file
fs.root.getFile(
file.name,
{ create: true },
function(fileEntry) {
// create a writer that can put data in the file
fileEntry.createWriter(function(writer) {
writer.onwriteend = function() {
// when done, continue to the next file
save(i + 1);
};
writer.onerror = err;
// this will read the contents of the current file
var fr = new FileReader;
fr.onloadend = function() {
// create a blob as that's what the
// file writer wants
var builder = new WebKitBlobBuilder;
builder.append(fr.result);
writer.write(builder.getBlob());
};
fr.onerror = err;
fr.readAsArrayBuffer(file);
}, err);
},
err
);
}
save(0);
});
$("ul").on("click", "li:not(:last)", function() {
// get the entry with this filename from the sandboxed filesystem
fs.root.getFile($(this).text(), {}, function(fileEntry) {
// get the file from the entry
fileEntry.file(function(file) {
// this will read the contents of the sandboxed file
var fr = new FileReader;
fr.onloadend = function() {
// log part of it
console.log(fr.result.slice(0, 100));
};
fr.readAsBinaryString(file);
});
}, err);
});
That is not possible, exactly, but your app can still probably work. Reading the file is possible through a file input form element, but writing the file back to disk is where you'll run into trouble.
The two ways your browser can write to disk are 1) downloading a file and 2) the HTML5 filesystem API. Option #1 obviously doesn't let your application choose the destination and option #2 only works with browser-created sandbox filesystems. That restriction might not be a deal-breaker for you -- it just means that the folders that your app uses will be buried somewhere in your browser's data files.
Also, the Filesystem API is currently Chrome-only (but it is an open standard). If you want cross-platform support, maybe you can use IndexedDB. You could use localStorage, but Chrome has a hard 5MB limit, which would be terrible for a media application.