Titanium save files from stream - file

I have a streamer from server(SOAP) with different type of files, and i what seve it in physical storage.
I try this code but i only create file with my string.
api.getFile(function(fileString) {
var original = 'Appcelerator';
var decoded = Ti.Utils.base64decode(fileString);
var Settings = Titanium.Filesystem.getFile(Titanium.Filesystem.tempDirectory, 'Settings');
var newFile = Titanium.Filesystem.getFile(Settings.nativePath, 'Settings.pdf');
newFile.createFile(decoded);
// Ti.API.info('newfile: '+newFile.read());
});
}
}

try this one..
var original = 'Appcelerator';
var decoded = Ti.Utils.base64decode(fileString);
var Settings = Titanium.Filesystem.getFile(Titanium.Filesystem.tempDirectory, 'Settings');
Settings.createDirectory();
var newFile = Titanium.Filesystem.getFile(Settings.nativePath, 'Settings.pdf');
newFile.write(decoded);

Related

Issue with Google Apps Script code copy-paste from Gsheet file

I've created a code to copy-paste the values from the most recent uploaded Gsheet file to another. The code is supposed to copy-paste only values that fulfil a cell condition.
The problem is, this code takes to long to run and doesn't finish to copy all values before having a run-time error.
The file has about 300.000 cells and the final amounts to be pasted on the 2nd file have about 90.000 cells.
Does anyone have a recommendation on how to proceed?
Thank you so much for your kind support.
function Master_Run_DB() {
Copy_EUDB();
}
function Copy_EUDB() {
var myLink = extractLink_EUDB();
sendData_EUDB(myLink);
}
function extractLink_EUDB() {
var newData = new Date().toLocaleString();
var drive = DriveApp.getFolderById("link to file");
var file = drive.getFilesByType(MimeType.GOOGLE_SHEETS);
var link = file.next().getUrl();
var ss = SpreadsheetApp.getActiveSpreadsheet();
return link
}
function sendData_EUDB(link) {
var mainSS = SpreadsheetApp.openById("link to file");
var lastRow = mainSS.getSheetByName("Database").getLastRow();
mainSS.getSheetByName("Database").getRange("A2" + ":R" + lastRow).clearContent();
var baseSS = SpreadsheetApp.openByUrl(link);
Logger.log(SpreadsheetApp.getActiveSpreadsheet().getUrl());
var lRow = baseSS.getSheetByName("Sheet1").getLastRow();
for (var i = 2; i <= lRow; i++) {
var cell = baseSS.getRange("G" + i);
var val = cell.getValue();
if (val == "EU") {
var sourceData = baseSS.getSheetByName("Sheet1").getRange("A" + i + ":R" + i).getValues();
var to = mainSS.getSheetByName("Database").getRange("A" + i + ":R" + i).setValues(sourceData);
}
}
};
Hello again,
Now that the new code is working, I was trying to add an IF AND clause to the copy-paste. The objective would be to copy only values that fulfil the following condition:
Column 7 = "EU"
Column 11 <> "CCCC"
But I'm getting a Syntax Error. Any advice?
Thank you in advance for your kind support
function Master_Run_EU() {
var drive = DriveApp.getFolderById("link to file");
var file = drive.getFilesByType(MimeType.GOOGLE_SHEETS);
var link = file.next().getUrl();
var ss = SpreadsheetApp.openById("link to file");
const sh=ss.getSheetByName('Database');
sh.getRange(2,1,sh.getLastRow(),22).clearContent();
var dbss = SpreadsheetApp.openByUrl(link);
const dbsh=dbss.getSheetByName('Sheet1');
var oA=[];
var vs=dbsh.getRange(2,1,dbsh.getLastRow()-1,22).getValues();
vs.forEach(function(r,i){
if(r[7]=="EU" && r[11]<>"CCCC") {
oA.push(r);
}
});
sh.getRange(2,1,oA.length,oA[0].length).setValues(oA);
}
Try this:
function Master_Run_DB() {
var drive = DriveApp.getFolderById("1ViOyzIkGOI6G6SMrtmPv4vjL-2-2duHC");
var file = drive.getFilesByType(MimeType.GOOGLE_SHEETS);
var link = file.next().getUrl();
var ss = SpreadsheetApp.openById("13CchyoqiWyvGTnYuG5TWA4cggBS-FsoDkW8XGesDkiY");
const sh=ss.getSheetByName('Database');
sh.getRange(2,1,sh.getLastRow(),18).clearContent();
var dbss = SpreadsheetApp.openByUrl(link);
const dbsh=dbss.getSheetByName('Sheet1');
var vs=dbsh.getRange(2,1,dbsh.getLastRow()-1,18).getValues();
vs.forEach(function(r,i){
if(r[6]=="EU") {
sh.getRange(i+2,1,1,18).setValues([r]);
}
});
}
It would be faster to do it this way:
function Master_Run_DB() {
var drive = DriveApp.getFolderById("1ViOyzIkGOI6G6SMrtmPv4vjL-2-2duHC");
var file = drive.getFilesByType(MimeType.GOOGLE_SHEETS);
var link = file.next().getUrl();
var ss = SpreadsheetApp.openById("13CchyoqiWyvGTnYuG5TWA4cggBS-FsoDkW8XGesDkiY");
const sh=ss.getSheetByName('Database');
sh.getRange(2,1,sh.getLastRow(),18).clearContent();
var dbss = SpreadsheetApp.openByUrl(link);
const dbsh=dbss.getSheetByName('Sheet1');
var oA=[];
var vs=dbsh.getRange(2,1,dbsh.getLastRow()-1,18).getValues();
vs.forEach(function(r,i){
if(r[6]=="EU") {
oA.push(r);
}
});
sh.getRange(2,1,oA.length,oA[0].length).setValues(oA);
}

Trying to copy specific file from specific folder in Google Drive

I'm trying to search for a specific file File1 in a specific folder (named through another variable).
Once I have identified the file, I want to make a copy of the file.
This is what I came up with, with the help of previous posts and many google searches but nothing happens.
var folderName = ConsultName;
var files = DriveApp.getFoldersByName(folderName).next().getFiles();
files.hasNext() && files == "File1" && files.next().makeCopy();
I've tried without the files == "File1" and the makeCopy() function will end up copying whatever file is next.
I've been trying to figure this out for several days, but haven't had any luck.
Any help would be helpful. Thanks!
I use these functions in several ways for loading and saving data in other scripts. If some arguments are omitted defaults are provided automatically. I believe you can use these building blocks to conjure up a copy solution for yourself
function loadFile(filename,folderID)
{
var filename = (typeof(filename) !== 'undefined')? filename : DefaultFileName;
var folderID = (typeof(folderID) !== 'undefined')? folderID : DataFolderID;
var fldr = DriveApp.getFolderById(folderID);
var file = fldr.getFilesByName(filename);
var s = '';
while(file.hasNext())
{
var fi = file.next();
var target = fi.getName();
if(target == filename)
{
s = fi.getBlob().getDataAsString();
}
}
return s;
}
function saveFile(datstr,filename,append)
{
var append = (typeof(append) !== 'undefined')? append : false;
var filename = (typeof(filename) !== 'undefined')? filename : DefaultFileName;
var datstr = (typeof(datstr) !== 'undefined')? datstr : '';
var folderID = (typeof(folderID) !== 'undefined')? folderID : DataFolderID;
var fldr = DriveApp.getFolderById(folderID);
var file = fldr.getFilesByName(filename);
var targetFound = false;
while(file.hasNext())
{
var fi = file.next();
var target = fi.getName();
if(target == filename)
{
if(append)
{
datstr = fi.getBlob().getDataAsString() + datstr;
}
targetFound = true;
fi.setContent(datstr);
}
}
if(!targetFound)
{
var create = fldr.createFile(filename, datstr);
if(create)
{
targetFound = true;
}
}
return targetFound;
}

Encode MP3 file to base64 string in Ionic

I'm working on a app that use cordova-plugin-media to record and audio file, and now I want to encode this file to base64 string, for now I can locate the file but when I try to encode it I get this :
"{"$$state":{"status":0}}"
Here is my code
audio.stopRecord();
audio.play();
if(device.platform == "iOS")
{
var path = cordova.file.tempDirectory;
}
else if(device.platform == "Android")
{
var path = cordova.file.externalRootDirectory;
}
var filename = name + extension;
var filepath = path + filename;
console.log(filepath);
console.log(JSON.stringify($cordovaFile.readAsDataURL(path, filename)));
file path : file:///storage/emulated/0/tPUhcxUKhmLUrWK3Qkqhc69OxeEIWyYrhEB0he9OwM0ffmjY2OUh3TLbFTsApdpIpjxyuC2wouyCs6m7uvdOCHCMiw9mbLMGYM25.mp3
Can any one help me with this??
Thanks
readAsDataURL needs a file object, it won't work with a string path.
Give the following code a try, working on iOS and Android
window.resolveLocalFileSystemURL(path, function(fileEntry) {fileEntry.file(function (file) {
var reader = new FileReader();
reader.onloadend = function(evt) {
var base64String = evt.target.result;
};
reader.readAsDataURL(file);
});}, function(e){console.log("error:" + JSON.stringify(e));});

Angularjs: create a link for download different types of file

Good day!
I can't resolve my problem - create link to download attachment.
A file I receive from SOAP service in xml and consequently I must create a link to download file.
What I have now:
In controller:
//creating comments
for (var index in $scope.comments){
var com = $scope.comments[index]
if (com.z2AF_Work_Log01_attachmentName !== undefined){
var a = document.createElement('a');
a.target = '_blank';
a.download = com.z2AF_Work_Log01_attachmentName;
a.innerText = com.z2AF_Work_Log01_attachmentName;
var blob = new Blob([ atob(com.z2AF_Work_Log01_attachmentData) ],
{ type : 'zip' });
//com.href = (window.URL || window.webkitURL).createObjectURL( blob );
a.href = (window.URL || window.webkitURL).createObjectURL( blob );;
com.attachment_link = a.outerHTML;
}
}
Links created, but if I have not plain text (csv) a file after download is broken. When I download csv - all fine.
In template:
.attach ng-bind-html="comment.attachment_link | notSanit"
After 3 days research I found the solution:
var decodeString = unescape(atob(attchment_data));
var ab = new ArrayBuffer(decodeString.length);
var ia = new Uint8Array(ab);
for (var i = 0; i < decodeString.length; i++) {
ia[i] = decodeString.charCodeAt(i);
}
var blob = new Blob([ab]);
href = (window.URL || window.webkitURL).createObjectURL( blob );

angular-file-upload with ngImgCrop

I'm using (ngImgCrop) to crop an image and then upload the cropped image to server using (angular-file-upload).
I can get the $dataURI from the "on-change" option in ngImgCrop. But I need a File instace to call $upload.
How can I get the File instance of the cropped image in order to upload :
$scope.upload = $upload.upload({
url: '/api/fileupload',
file: [**file cropped here**]
}).progress(function (evt) {
//
}).success(function (data, status, headers, config) {
//
});
I guess you'll find a proper answer in this method. I found it in Github, in the angular-file-upload issues page (https://github.com/nervgh/angular-file-upload/issues/208):
/**
* Converts data uri to Blob. Necessary for uploading.
* #see
* http://stackoverflow.com/questions/4998908/convert-data-uri-to-file-then-append-to-formdata
* #param {String} dataURI
* #return {Blob}
*/
var dataURItoBlob = function(dataURI) {
var binary = atob(dataURI.split(',')[1]);
var mimeString = dataURI.split(',')[0].split(':')[1].split(';')[0];
var array = [];
for(var i = 0; i < binary.length; i++) {
array.push(binary.charCodeAt(i));
}
return new Blob([new Uint8Array(array)], {type: mimeString});
};
You should be able to get a file instance doing something like this:
var blob = dataURItoBlob($scope.croppedImage);
I don't know if it works in the good way, but it seems.
try something like:
var uploader = $scope.uploader = new FileUploader({
url: '/saveImagePath',
autoUpload: false
});
angular.element(document.querySelector('#fileInput')).on('change',handleFileSelect);
var handleFileSelect=function(evt) {
var file=evt.currentTarget.files[0];
var reader = new FileReader();
reader.onload = function (evt) {
$scope.$apply(function($scope){
$scope.myImage=evt.target.result;
});
};
reader.readAsDataURL(file);
};
the uploader doesn't support base64 images so you'll need to convert the cropped image from base64 to blob
function base64ToBlob(base64Data, contentType) {
contentType = contentType || '';
var sliceSize = 1024;
var byteCharacters = atob(base64Data);
var bytesLength = byteCharacters.length;
var slicesCount = Math.ceil(bytesLength / sliceSize);
var byteArrays = new Array(slicesCount);
for (var sliceIndex = 0; sliceIndex < slicesCount; ++sliceIndex) {
var begin = sliceIndex * sliceSize;
var end = Math.min(begin + sliceSize, bytesLength);
var bytes = new Array(end - begin);
for (var offset = begin, i = 0 ; offset < end; ++i, ++offset) {
bytes[i] = byteCharacters[offset].charCodeAt(0);
}
byteArrays[sliceIndex] = new Uint8Array(bytes);
}
return new Blob(byteArrays, { type: contentType });
}
you have to manually attach the files to the queue like this:
$scope.submit = function () {
var file = base64ToBlob($scope.currentPortfolio.croppedImage.replace('data:image/png;base64,',''), 'image/jpeg');
uploader.addToQueue(file);
uploader.uploadAll();
};
in the server side, you got two types of files one posted as HTML file and another un base64 which is the cropped image.

Resources