How to create a new file in appcelerator titanium.
var Settings = Titanium.Filesystem.getFile(Titanium.Filesystem.tempDirectory,'Settings');
Ti.API.info("Created Settings: " + Settings.createDirectory());
Ti.API.info('Settings ' + Settings);
var newFile = Titanium.Filesystem.getFile(Settings.nativePath,'Settings.txt');
newFile.write('line 1\n');
Ti.API.info('newfile: '+newFile.read());
The Above code is not working...
Try creating the file before writing to the file:
var Settings = Titanium.Filesystem.getFile(Titanium.Filesystem.tempDirectory,'Settings');
Ti.API.info("Created Settings: " + Settings.createDirectory());
Ti.API.info('Settings ' + Settings);
var newFile = Titanium.Filesystem.getFile(Settings.nativePath,'Settings.txt');
newFile.createFile();
if (newFile.exists()){
newFile.write('line 1\n');
Ti.API.info('newfile: '+newFile.read());
}
Using newFile.createFile(); will throw error. It seems depricated in 3.0 as I did not find it woking with me. I tried newfile.write('Some data'); and it worked.
Related
I am using the script below to export a sheet as Excel file but the output file name is always Document Name + Sheet Name ("Exported - Report.xlsx"). How can I modify this to only use the sheet name as file name of the exported file ("Report.xlsx")?
function ExportSheet()
{
var SheetApp = SpreadsheetApp.getActive();
SheetApp.rename("Exported");
ShtURL = SheetApp.getUrl();
ShtID = SheetApp.getId();
ShtGID = SheetApp.getSheetId();
var url = ShtURL.toString().replace("/edit", "/export?format=xlsx&gid=" + ShtGID);
var html = HtmlService.createHtmlOutput('<html><script>'
+'window.close = function(){window.setTimeout(function(){google.script.host.close()},9)};'
+'var a = document.createElement("a"); a.href="'+url+'"; a.target="_blank";'
+'if(document.createEvent){'
+' var event=document.createEvent("MouseEvents");'
+' if(navigator.userAgent.toLowerCase().indexOf("firefox")>-1){window.document.body.append(a)}'
+' event.initEvent("click",true,true); a.dispatchEvent(event);'
+'}else{ a.click() }'
+'close();'
+'</script>'
// Offer URL as clickable link in case above code fails.
+'<body style="word-break:break-word;font-family:sans-serif;">Failed to open automatically. Click here to proceed.</body>'
+'<script>google.script.host.setHeight(40);google.script.host.setWidth(410)</script>'
+'</html>')
.setWidth( 90 ).setHeight( 1 );
SpreadsheetApp.getUi().showModalDialog( html, "Opening ..." );
SheetApp.rename("Template");
}
In your situation, unfortunately, using the URL of ShtURL.toString().replace("/edit", "/export?format=xlsx&gid=" + ShtGID), the filename cannot be directly changed. So, in this case, how about the following modification?
Modified script:
function ExportSheet() {
var SheetApp = SpreadsheetApp.getActive();
SheetApp.rename("Exported");
ShtURL = SheetApp.getUrl();
ShtID = SheetApp.getId();
ShtGID = SheetApp.getSheetId();
var url = ShtURL.toString().replace("/edit", "/export?format=xlsx&gid=" + ShtGID);
// --- I modified below script.
var blob = UrlFetchApp.fetch(url, { headers: { authorization: "Bearer " + ScriptApp.getOAuthToken() } }).getBlob();
var file = DriveApp.createFile(blob.setName(SheetApp.getSheets()[0].getSheetName()));
url = "https://drive.google.com/uc?export=download&id=" + file.getId();
// ---
var html = HtmlService.createHtmlOutput('<html><script>'
+ 'window.close = function(){window.setTimeout(function(){google.script.host.close()},9)};'
+ 'var a = document.createElement("a"); a.href="' + url + '"; a.target="_blank";'
+ 'if(document.createEvent){'
+ ' var event=document.createEvent("MouseEvents");'
+ ' if(navigator.userAgent.toLowerCase().indexOf("firefox")>-1){window.document.body.append(a)}'
+ ' event.initEvent("click",true,true); a.dispatchEvent(event);'
+ '}else{ a.click() }'
+ 'close();'
+ '</script>'
// Offer URL as clickable link in case above code fails.
+ '<body style="word-break:break-word;font-family:sans-serif;">Failed to open automatically. Click here to proceed.</body>'
+ '<script>google.script.host.setHeight(40);google.script.host.setWidth(410)</script>'
+ '</html>')
.setWidth(90).setHeight(1);
SpreadsheetApp.getUi().showModalDialog(html, "Opening ...");
SheetApp.rename("Template");
file.setTrashed(true); // Added
}
In this modification, the converted XLSX is created as a temporal file. Here, the filename is changed. And, the file is downloaded using the URL of the created file. The temporal file is removed.
Note:
From your script, I thought that you might have wanted to use the sheet name of the 1st tab. But, if you want to give the specific filename, please modify SheetApp.getSheets()[0].getSheetName() of blob.setName(SheetApp.getSheets()[0].getSheetName()).
I'm trying to do automate my file saving to saveAs file .rgba in photoshop. So far I only manage to modify the code to save out .sgi files. Please help. Thanks
var Name = app.activeDocument.name.replace(/\.[^\.]+$/,'');
var Path = app.activeDocument.path;
var saveFile = File(Path + "/" + Name +".sgi");
var saveFile2 = File(Path + "/" + Name +".rgba");
if(saveFile2.exists)
{
saveFile2.remove();
}
rgbaSaveOptions = new SGIRGBSaveOptions();
activeDocument.saveAs(saveFile, rgbaSaveOptions, true, Extension.LOWERCASE);
saveFile.rename(Name+'.rgba');
I'm building an app with PhoneGap Build, only targeting Android. One of the features is to download a file from a web server to the device.
This code works perfectly on Android 4.x, but doesn't work on Android 5.x and above:
var URL = 'https://example.com/path/to/file.pdf?auth_token=123xxxx';
var Folder_Name = 'Download';
var File_Name = URL.split('/');
File_Name = File_Name[File_Name.length - 1].split('?');
File_Name = File_Name[0];
window.requestFileSystem(LocalFileSystem.PERSISTENT, 0, fileSystemSuccess, fileSystemFail);
function fileSystemSuccess(fileSystem) {
var download_link = encodeURI(URL);
var directoryEntry = fileSystem.root; // to get root path of directory
directoryEntry.getDirectory(Folder_Name, {
create: true,
exclusive: false
}, onDirectorySuccess, onDirectoryFail); // creating folder in sdcard
var rootdir = fileSystem.root;
var fp = rootdir.toURL(); // Returns Fullpath of local directory
fp = fp + "/" + Folder_Name + "/" + File_Name; // fullpath and name of the file which we want to give
console.log("Path to local file: " + fp);
// download function call
filetransfer(download_link, fp);
}
function onDirectorySuccess(parent) {
console.log('directory created successfully');
// Directory created successfuly
}
function onDirectoryFail(error) {
//Error while creating directory
console.log("Unable to create new directory: " + error.code);
}
function fileSystemFail(evt) {
//Unable to access file system
console.log(evt.target.error.code);
}
function filetransfer(download_link, fp) {
var fileTransfer = new FileTransfer();
// File download function with URL and local path
fileTransfer.download(download_link, fp,
function(entry) {
alert('The file was successfully downloaded, you can access it in /' + Folder_Name + '/' + File_Name + '.');
console.log("download complete: " + entry.fullPath);
},
function(error) {
//Download abort errors or download failed errors
console.log("download error source " + error.source);
console.log("download error target " + error.target);
console.log("download error code" + error.code);
}
);
}
Don't get anything in the console, no error and none of the log lines, meaning that none of the callbacks gets triggered.
Did anybody else have this mysterious issue?
Thanks
try to install these versions.
phonegap plugin remove cordova-plugin-file
phonegap plugin remove cordova-plugin-file-transfer
phonegap plugin add cordova-plugin-file#4.3.3
phonegap plugin add cordova-plugin-file-transfer#1.5.1
I am use these versions and i havent problems in Anrdoid 5, 6, 7. Try it.
having a bit of trouble with my download function for Cordova. I have a function here:
document.addEventListener("deviceready", function () {
var fileUrl = e.target.getAttribute('data-soundurl');
console.log(fileUrl);
//returns as "../www/card-sounds/sound2.m4a"
var fileOutputPath = e.target.getAttribute('data-quote') + ".m4a";
console.log(fileOutputPath);
//returns as "Sound Title.m4a"
var fileTransfer = new FileTransfer();
var output = "file:///android_asset/www/res/db/"+fileOutputPath;
fileTransfer.download(
fileUrl,
output,
function(entry) {console.log("download complete: " + entry.toURL());},
function(error) {console.log("download error source " + error.source);
console.log("download error target " + error.target);
console.log("upload error code" + error.code);
},
false,
{headers:{"Authorization": "Basic dGVzdHVzZXJuYW1lOnRlc3RwYXNzd29yZA=="}}
);
console.log(output);
//returns as "file:///android_asset_www_res/db/Sound Title.m4a"
}, true);
And my log output just shows:
download error source null
download error target null
upload error codenull
I can't seem to get any sort of .root part of the FileSystem to actually give me a defined string so I'm just trying to get it to download to Android for now. Am I doing something fundamentally wrong? I am so confused here.
Try this :
var output = "/res/db/"+fileOutputPath;
For your output use
var output = cordova.file.externalRootDirectory + fileOutputPath;
cordova.file.externalRootDirectory should give you something like "file:///storage/emulated/0/"
I want to create a copy of document in the SharePoint document library.
Basically let us assume there is a template and every user will open the document by clicking on it. I want to create a copy of file user has clicked and open that file for editting.
I have tried using JavaScript Client Object model of SharePoint. But the examples are for manipulating list items but not for document library.
Can any one please point to any sources that I can use to manipulate the files in document library
One restriction being I need to use JavaScript object model or web services to achive this functionality. i.e., NO server side code
Following is the code I got till now
The approach I am planning to use is copy the existing file object
Rename it and
Save it to other document library
Please ignore formatting as I am not able to do it properly and this is under development code
<script type="text/javascript">
var clientContext = null;
var web = null;
var meetingItems = null;
var filePath = null;
var file = null;
debugger;
ExecuteOrDelayUntilScriptLoaded(Initialize, "sp.js");
function Initialize() {
clientContext = new SP.ClientContext.get_current();
web = clientContext.get_web();
this.list = web.get_lists().getByTitle("Documents");
clientContext.load(list, 'Title', 'Id');
var queryStart = "<View>"+ "<Query>"+ "<Where>"+ "<Eq>"+ "<FieldRef Name='Title'/>" + "<Value Type='Text'>";
var queryEnd = "</Value>"+ "</Eq>"+ "</Where>"+ "</Query>"+ "</View>";
camlQuery = new SP.CamlQuery();
queryMeeting = queryStart + 'DevCookbook'+ queryEnd;
camlQuery.set_viewXml(queryMeeting);
meetingItems = list.getItems(camlQuery);
clientContext.load(meetingItems);
clientContext.executeQueryAsync(Function.createDelegate(this, this.onListLoadSuccess), Function.createDelegate(this, this.onQueryFailed));
}
function onListLoadSuccess(sender, args) {
filePath = meetingItems.get_item(0).get_path();
file = meetingItems.get_item(0);
debugger;
clientContext.load(file);
clientContext.executeQueryAsync(Function.createDelegate(this, this.onFileLoadSuccess), Function.createDelegate(this, this.onFileFailed));
// alert("List title : " + this.list.get_title() + "; List ID : " + this.list.get_id());
// doclist();
}
function doclist()
{
var path = file.get_title();
path = meetingItems.get_item(0).get_file().get_title();
}
function onQueryFailed(sender, args) {
alert('request failed ' + args.get_message() + '\n' + args.get_stackTrace());
}
function onFileLoadSuccess(sender, args) {
debugger;
alert("List title : " + this.list.get_title() + "; List ID : " + this.list.get_id());
}
function onFileFailed(sender, args) {
alert('request failed ' + args.get_message() + '\n' + args.get_stackTrace());
}
</script>
I used copy webservice to do the functionality.
Approach is combination of Object Model and JavaScript functions
Copy the file from templates library.
Check out file using "CheckoutDocument" function
Add metadata in background
Show edits metadata pop up to user using
var oDialog = {
url: "../Library/Forms/Edit.aspx?ID=" + itemID,
title: "Create a new document"
};
SP.UI.ModalDialog.showModalDialog(oDialog)
After user input check in the document