DriveApp.createFile( e.parameter.blob); Not executing - google-apps-script

In google app scripts, the following line throws error:
DriveApp.createFile( e.parameter.fileupBlob);
Where fileupBlob is hidden field in the form with a BLOB stored in it.
Error thrown when executed:
Cannot find method createFile((class)). (line 23, file "Code", project
"saving")

The argument of DriveApp.createFile must be a blob.
The value returned by e.parameter.varName is a string.
Therefore the error you get. The only case when a blob is returned from a form is when you use a file upload widget, the hidden widget behaves like a text widget.

You need to create the blob as shown below. It is assuming you passed a valid blob. EDIT: If drive is having difficulty figuring out what type of file it is from the blob you can provide that info yourself. Another thought is that the blob may be base64 encoded. You may have to decode it before creating the new blob. You haven't posted any code so I can't tell what is going on.
var name = "fileName.png";
var contentType = "image/png";
var fileBlob = Utilities.newBlob(e.parameter.fileupBlob, contentType, name);
DriveApp.createFile(fileBlob);

Do this
let imageBlob = images[0].getBlob();
let name = 'fileName.jpeg';
let contentType = 'image/jpeg';
let fileBlob = Utilities.newBlob(imageBlob.getBytes(), contentType, name);
let imageFile = folder.createFile(fileBlob).setName('ravgeet.jpeg');

Got it! The javascript library was returning string dataURI and i replaced the first part of dataURI in jquery:
strDataURI=strDataURI.replace("data:image/png;base64,", "");
document.getElementById("blobobj").value = strDataURI;
Then i was able to create the image
var str=Utilities.base64Decode(e.blobobj);
var fileBlob = Utilities.newBlob(str).setContentType('image/png');

Related

Why does uploading a .csv file to S3 get converted to a json

I am trying to upload a file to S3 using apps script.
I have been trying to use https://github.com/viuinsight/google-apps-script-for-aws
S3.init();
S3.putObject("bucket123", 'Tacofile.txt', content, 'ca-central-1')
I retrieve a file from Google Workspace, where 'Tacofile' is a .txt file
The file successfully loads to S3
The file, however, somehow gets converted to json? How to keep the file as a csv or is there a way to specify the MIME type somewhere before the upload?
thanks in advance
CB
Yes use File.getBlob() S3.putObject("bucket123", 'Tacofile.txt', content.getBlob(), 'ca-central-1')
#theWizEd thanks for pointing me in the right direction! I think I got this to work. I changed my source data so my download was done using:
object = DriveApp.getFileById(file_id).getBlob().getDataAsString();
i changed the section in line 106 below:
if (notBlob) {
object = Utilities.newBlob(JSON.stringify(object), "application/json");
object.setName(objectName);
}
var content = object.getDataAsString();
var contentType = object.getContentType();
var contentMD5 = getContentMD5(content);
to the following
if (notBlob) {
//object = Utilities.newBlob(JSON.stringify(object), "application/json");
//object.setName(objectName);
}
var content = object;
var contentType = MimeType.PLAIN_TEXT
var contentMD5 = getContentMD5(content);

How do you POST files in chunks, to server, using input id as param, in HTML/jQuery?

Description
I have a function that takes HTTP_POST path for server side hardcoded .js handler and file id from input[type=file]. I'm trying to POST that binary file to server but in chunks with no success.
What have you tried?
Using my uncle wisdom, I have noted that there is a way to slice the file using :
var File1 = document.querySelector('input').files[0].slice(0,7);
But passing this variable to the function is not an option since it takes id ="file_1" as a parameter from <input type="file">. Also, printing this variable doesn't work with console.log (half of you are already thinking to send me back to uni) hint: I've never studied Javascript. So I poked my uncle a little harder and found it. FileReader gives you the ability to actually read the inside, which gave me hope since my file was printed out to console.log
var reader = new FileReader;
reader.readAsBinaryString(File1);
reader.onload = function(e) {
var rawLog = reader.result;
console.log(rawLog);
};
At this point console.log gave me a print of first seven bytes, of my file. And by all of this we got to the question I wish to ask
Question ?¿
How to past this print as with input to the function so I can have this file sliced and saved?
You can slice off a piece of the file, use that piece to create a File object add it to a FileList and then overwrite the FileList from the input with the one that has your new file
var input = document.querySelector('input');
var originalfile = input.files[0];
var slice = originalfile.slice(0,7); // slice the file
var newfile = new File([slice] , 'slicedfile.dat'); // create new file
// Need to use a data transfer object to get a new FileList object
var datTran = new ClipboardEvent('').clipboardData || new DataTransfer();
datTran.items.add(newfile); // Add the file to the DT object
input.files = datTran.files; // overwrite the input file list with ours
// call function that takes path and id as parameters

Why is this Importxml formula not working?

The following formula does work for some, but not for others:
=IFNA(VALUE(IMPORTXML("https://finance.yahoo.com/quote/C2PU.SI", "//*[#class=""D(ib) Mend(20px)""]/span[1]")))
If used without IFNA, it says 'Resource at url not found'.
Here's the value I'm trying to pull in:
I appreciate if you could point me to the right direction.
Thank you!
It does not return any values even for simple importxml.
It seems the site is generated by javascript or protected so it can't be scraped by importxml.
Don't use the "inspect" tool as it will show the DOM as it's being rendered by the web browser including modifications to the source code by client-side JavaScript, instead look at the source code.
Resources
How to know if Google Sheets IMPORTDATA, IMPORTFEED, IMPORTHTML or IMPORTXML functions are able to get data from a resource hosted on a website?
The structure of the DOM is generated by javascript. Nevertheless, all informations you need are contained by a json string called here root.App.main. You can get all the data by these way
function extract(url){
var source = UrlFetchApp.fetch(url).getContentText()
return source.match(/(?<=root.App.main = ).*(?=}}}})/g) + '}}}}'
}
and then retrieve the data by conventionnal json parsing. This will give you the value
[![function marketPrice() {
var code = 'C2PU.SI'
var url='https://finance.yahoo.com/quote/' + code
var source = UrlFetchApp.fetch(url).getContentText()
var jsonString = source.match(/(?<=root.App.main = ).*(?=}}}})/g) + '}}}}'
var data = JSON.parse(jsonString)
var regularMarketPrice = data.context.dispatcher.stores.StreamDataStore.quoteData.item(code).regularMarketPrice.raw
Logger.log(regularMarketPrice)
}
Object.prototype.item=function(i){return this\[i\]};][1]][1]

Is there a way to modify json received callback?

I'm receiving a callback from a server in my Google app script via doPost.
The problem is, my Json format is with a this word in front of the Json "Data=", because of that I'm not able to work with the Json callback.
The code:
Function doPost(e){
var r = e.postdata.contents
Logger.log(r)
}
I'm receiving the bellow format.
data={""retorno"":{""estoques"":[{""estoque"":{""codigo"":""001a"",""nome"":""M\u00e1scara 100% Algod\u00e3o Lav\u00e1vel Dupla Prote\u00e7\u00e3o - 10 Unidades"",""estoqueAtual"":50,""depositos"":[{""deposito"":{""id"":7939278964,""nome"":""Geral"",""saldo"":""50.0000000000"",""desconsiderar"":""N"",""saldoVirtual"":""50.0000000000""}}]}}]}}
Anyway to remove this "Data="?
Thanks
If you just want to remove the substring data= - the easiest would be to use the method silce()
Sample:
var r = e.postdata.contents;
var sliced = r.toString().slice(5);
Logger.log(slide);

Google Apps Script Utilities.base64Decode Exception: Could not decode string

I have base64 encoded png image which is placed in Google Sheet cell. Need to decode this in Google App Script to image and using following code.
=============================================================
CODE
var ss = SpreadsheetApp.getActiveSheet();
var strBase64Image = ss.getRange('F1').getValue()
ss.getRange('F2').setValue(strBase64Image); // test fn is working
var decodedBytes = Utilities.base64Decode(strBase64Image); // decode to byte array
var blobImg = Utilities.newBlob(decodedBytes, MimeType.PNG); // create blog from byte array
ss.insertImage(blobImg, 6, 3); // write image to F3 cell
=============================================================
ERROR
Exception: Could not decode string.
=============================================================
This base64 encoded png image string is getting decoded to image when tested in https://codebeautify.org/base64-to-image-converter
Thanks,
Nilesh Korde
Two things:
You need to strip off data:image/png;base64, from your Base64 string - the presence of this header is what gives you the error
Exception: Could not decode string.
When you create the blob, you need to give it a name: var blobImg = Utilities.newBlob(decodedBytes, MimeType.PNG, 'MyImageName'); - as featured in the sample code here.
Otherwise you will get the error
Exception: Unexpected error while getting the method or property insertImage on object SpreadsheetApp.Sheet..