How to save or open a pdf file in pdf Viewer from response titanium - titanium

I want to open pdf file on click.
I tried below code but it didn't help me. It is giving error could not read file
var xhr = Ti.Network.createHTTPClient({
onload : function(e) {
var f = Ti.Filesystem.getFile(Ti.Filesystem.applicationDataDirectory, 'file.pdf');
Ti.API.info('file == ' + f);
Ti.API.info('response = ' + this.responseData);
Ti.API.info('response = ' + JSON.stringify(this.responseData));
f.write(this.responseData);
Ti.API.info('write file == ' + f.write(this.responseData));
Ti.API.info('filepath == ' + f.nativePath);
Ti.API.info('get filepath == ' + f.getNativePath());
Ti.Android.currentActivity.startActivity(Ti.Android.createIntent({
action : Ti.Android.ACTION_VIEW,
type : 'application/pdf',
data : f.nativePath
}));
},
onerror : function(e) {
Alloy.Globals.loading.hide();
alert("Cannot retrieve PDF form web site");
},
timeout : 5000
});
xhr.open('GET', "https://www.mbta.com/uploadedfiles/Documents/Schedules_and_Maps/Rapid%20Transit%20w%20Key%20Bus.pdf");
xhr.send();
But I am getting Error as The document path is not valid.
I tried different way also using webview still not getting pdf on my app.
var win = Ti.UI.createWindow({
backgroundColor : '#fff'
});
var pdfViewer = Ti.UI.createWebView({
url : "http://lkn.ccomsys.com/assets/media/datafiles/gov/vvvv_Shehnai_Order1.pdf",
width : Titanium.UI.SIZE,
height : Titanium.UI.SIZE
});
Ti.API.info('pdfviewer == ' + JSON.stringify(pdfViewer));
win.add(pdfViewer);
win.open();
Thanks in advance.

I sorted this out
Step 1 : Created directory and file.
Step 2 : Write response to created file.
Step 3 : Open pdf with android intent.
Below is the complete code
var xhr = Ti.Network.createHTTPClient({
onload : function(e) {
Alloy.Globals.loading.hide();
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, 'Setting.pdf');
Ti.API.info('new file == ' + newFile);
if (newFile.exists() === false) {
// you don't need to do this, but you could...
newFile.write(this.responseData);
}
Ti.API.info('response = ' + this.responseData);
Ti.API.info('response = ' + JSON.stringify(this.responseData));
if (newFile.exists()) {
newFile.write(this.responseData);
Ti.API.info('newfile: ' + newFile.read());
}
Ti.Android.currentActivity.startActivity(Ti.Android.createIntent({
action : Ti.Android.ACTION_VIEW,
type : 'application/pdf',
data : newFile.nativePath
}));
},
onerror : function(e) {
Alloy.Globals.loading.hide();
alert("Cannot retrieve PDF form web site");
},
timeout : 5000
});
xhr.open('GET', "https://www.mbta.com/uploadedfiles/Documents/Schedules_and_Maps/Rapid%20Transit%20w%20Key%20Bus.pdf");
xhr.send();

Related

Create PDF with name instead of creating the file in drive and renaming

Currently my script saves the PDF with the name export.pdf and then renames it to the value I have in one of the cells of my spreadsheet, the problem with that is that my website's API ends up taking the file when it is created and all are collected like export.pdf instead of the name I really need.
Is there an option to create the PDF with the correct name instead of renaming it?
//Create PDF
SpreadsheetApp.flush();
var theurl = 'https://docs.google.com/a/mydomain.org/spreadsheets/d/' +
'IDSPREADSHEETIDSPREADSHEETIDSPREADSHEET' +
'/export?format=pdf' +
'&size=0' +
'&portrait=true' +
'&fitw=true' +
'&top_margin=0' +
'&bottom_margin=0' +
'&left_margin=0' +
'&right_margin=0' +
'&sheetnames=false&printtitle=false' +
'&pagenum=false' +
'&gridlines=false' +
'&fzr=FALSE' +
'&gid=' +
'IDPAGEIDPAGEIDPAGEIDPAGE';
var token = ScriptApp.getOAuthToken();
var docurl = UrlFetchApp.fetch(theurl, { headers: { 'Authorization': 'Bearer ' + token } });
var pdfBlob = docurl.getBlob();
//...get token and Blob (do not create the file);
var fileName = ss.getSheetByName("Gerais").getRange("H2").getValue();
//Access or create the 'Squads' folder;
var folder;
var folders = DriveApp.getFoldersByName("Squads");
if(folders.hasNext()) {
folder = folders.next();
}else {
folder = DriveApp.createFolder("Squads");
}
//Remove duplicate file with the same name;
var existing = folder.getFilesByName(fileName);
if(existing.hasNext()) {
var duplicate = existing.next();
if (duplicate.getOwner().getEmail() == Session.getActiveUser().getEmail()) {
var durl = 'https://www.googleapis.com/drive/v3/files/'+duplicate.getId();
var dres = UrlFetchApp.fetch(durl,{
method: 'delete',
muteHttpExceptions: true,
headers: {'Authorization': 'Bearer '+token}
});
var status = dres.getResponseCode();
if (status >=400) {
} else if (status == 204) {
folder.createFile(pdfBlob).setName(fileName);
}
}
} else {
folder.createFile(pdfBlob).setName(fileName);
Issue:
Setting file name after creating file
folder.createFile(pdfBlob).setName(fileName);
Solution:
Set the blob name before creating file:
folder.createFile(pdfBlob.setName(fileName));

Getting Bad method 405 response while trying to upload a file to Google Cloud Storage using SAP ui5

I am trying to upload a file to Google Cloud Storage using a basic uploader in UI5.
When I am uploading the file, I am getting a 405 error in my response.
My controller code goes like this.
Please let me know if I am making any mistake anywhere.
sap.ui.define(['sap/m/MessageToast','sap/ui/core/mvc/Controller'],
function(MessageToast, Controller) {
"use strict";
return Controller.extend("sap.ui.unified.sample.FileUploaderBasic.Controller", {
handleUploadComplete: function(oEvent) {
var sResponse = oEvent.getParameter("response");
if (sResponse) {
var sMsg = "";
var m = /^\[(\d\d\d)\]:(.*)$/.exec(sResponse);
if (m[1] == "200") {
sMsg = "Return Code: " + m[1] + "\n" + m[2] + "(Upload Success)";
oEvent.getSource().setValue("");
} else {
sMsg = "Return Code: " + m[1] + "\n" + m[2] + "(Upload Error)";
}
MessageToast.show(sMsg);
}
},
handleUploadPress: function() {
var oFileUploader = this.byId("fileUploader");
var prop = oFileUploader.getValue();
var path = oFileUploader.getUploadUrl();
MessageToast.show(prop);
MessageToast.show(path);
// var form = new FormData();
//form.append("files", fileInput.files[0],"C:\Users\i347520\Desktop\pan.jpg");
/*eslint-disable*/
var settings = {
"url": "https://storage.googleapis.com/upload/storage/v1/b/testocr-1234/o?uploadType=media&name=prop"
/*eslint-enable*/
};
oFileUploader.upload(settings);
}
});
});
View:
<mvc:View
controllerName="sap.ui.unified.sample.FileUploaderBasic.Controller"
xmlns:l="sap.ui.layout"
xmlns:u="sap.ui.unified"
xmlns:mvc="sap.ui.core.mvc"
xmlns="sap.m"
class="viewPadding">
<l:VerticalLayout>
<u:FileUploader
id="fileUploader"
name="myFileUpload"
uploadUrl="upload/"
tooltip="Upload your file to the local server"
uploadComplete="handleUploadComplete"/>
<Button
text="Upload File"
press="handleUploadPress"/>
</l:VerticalLayout>
</mvc:View>

openui5 FileUploader not working

I am trying to upload a file with a simple form. I can choose a file but when I click on "upload" nothing happens.
My FileUploader.view.xml is like:
<mvc:View
controllerName="sap.ui.unified.sample.FileUploaderBasic.Controller"
xmlns:l="sap.ui.layout"
xmlns:u="sap.ui.unified"
xmlns:mvc="sap.ui.core.mvc"
xmlns="sap.m"
class="viewPadding">
<l:VerticalLayout>
<u:FileUploader
id="fileUploader"
name="myFileUpload"
uploadUrl="upload/"
width="400px"
tooltip="Upload your file to the local server"
uploadComplete="handleUploadComplete"/>
<Button
text="Upload File"
press="handleUploadPress"/>
</l:VerticalLayout>
My Contoller.controller.js
sap.ui.define(['sap/m/MessageToast','sap/ui/core/mvc/Controller'],
function(MessageToast, Controller) {
"use strict";
var ControllerController = Controller.extend("sap.ui.unified.sample.FileUploaderBasic.Controller", {
handleUploadComplete: function(oEvent) {
var sResponse = oEvent.getParameter("response");
if (sResponse) {
var sMsg = "";
var m = /^\[(\d\d\d)\]:(.*)$/.exec(sResponse);
if (m[1] == "200") {
sMsg = "Return Code: " + m[1] + "\n" + m[2] + "(Upload Success)";
oEvent.getSource().setValue("");
} else {
sMsg = "Return Code: " + m[1] + "\n" + m[2] + "(Upload Error)";
}
MessageToast.show(sMsg);
}
},
handleUploadPress: function(oEvent) {
var oFileUploader = this.getView().byId("fileUploader");
oFileUploader.upload();
}
});
return ControllerController;
});
When I run this in the debugger I get an Uncaught TypeError:
Uncaught TypeError: Cannot read property '1' of null
at f.handleUploadComplete (FileUploader.controller.js?eval:11)
at f.a.fireEvent (EventProvider-dbg.js:229)
at f.a.fireEvent (Element-dbg.js:427)
at f.fireUploadComplete (ManagedObjectMetadata-dbg.js:426)
at HTMLIFrameElement.eval (FileUploader.js?eval:6)
at HTMLIFrameElement.dispatch (jquery-dbg.js:4737)
at HTMLIFrameElement.c3.handle (jquery-dbg.js:4549)
if (m[1] == "200") {
sMsg = "Return Code: " + m[1] + "\n" + m[2] + "(Upload Success)";
oEvent.getSource().setValue("");
I searched for sample code and it seems my code is ok, but I don't know why I can't upload a file by click on the button.
I solved this problem ! :)
So, instead of using this
var m = /^[(\d\d\d)]:(.)$/.exec(sResponse);
use this in view FileUploader :
sendXHR="true"
After, on controller js you can use for status :
oEvent.getParameter("status")
and for getting answer as a json file :
var jsonfile = JSON.parse(oEvent.getParameter("responseRaw"));
Then access your sent object attributes from server (only when use dataType: 'json')
jsonfile.attribute
I hope this helps a lot!

OL3 add backup url

I'm trying to add a backup route for a tiles with ol3. I would like to test on the errorload event if the source url starting by "http".
If "yes" : replace this tile by a custom tile.
If "no" : change the source url of this tile by another one and retry
I think i need to use something like that :
layerTile.getSource().setUrl('file:///local/{z}/{x}/{y}.jpg');
var errorTilePath='https://image.noelshack.com/fichiers/2017/14/1491403614-errortile.png';
var serverBackup='http://otile1.mqcdn.com/tiles/1.0.0/map/';
layerTile.getSource().setTileLoadFunction((function() {
var tileLoadFn = layerTile.getSource().getTileLoadFunction();
return function(tile, src) {
var image = tile.getImage();
image.onload = function() {console.log('Tile ok : ' + src); };
image.onerror = function() {
console.log('Tile error : ' + src);
console.log(tile);
if (src.substr(0,4)!='http') {
var tmp=src.split('/').reverse();
var serverBackupPath=serverBackup+tmp[2]+'/'+tmp[1]+'/'+tmp[0].split('.')[0]+'.png';
console.log("Second url : " + serverBackupPath)
src=serverBackupPath;
tile.getImage().src=src;
var image = tile.getImage();
image.onload = function() {console.log('Tile backup ok : ' + src);};
image.onerror = function() {console.log('Tile backup error : ' + src); src=errorTilePath; tile.getImage().src=src; tileLoadFn(tile, src);}
} else {
console.log('Custom tile : ');
src=errorTilePath;
tile.getImage().src=src;
}
tileLoadFn(tile, src);
};
tileLoadFn(tile, src);
};
})());
With that, I can see that the backup tile is downloaded but not visible on map.
Certainely, I misunderstood something.
Thanks in advance if somebody could help me.
Oups, without code my answer is null.
layerTile.getSource().setUrl('file:///local/{z}/{x}/{y}.jpg');
var serverBackup='https://{a-c}.tile.openstreetmap.org/';
var errorTilePath=urlBase+'css/images/error.png';
layerTile.getSource().setTileLoadFunction((function() {
return function(tile, src) {
if (UrlExists(src)) {
tile.getImage().src=src;
} else {
if (src.substr(0,4)=='file') {
var tmp=src.split('/').reverse();
src='https://'+['a', 'b', 'c'].sort(function() {return 0.5 - Math.random()})[0]+'.tile.openstreetmap.org/'+tmp[2]+'/'+tmp[1]+'/'+tmp[0].split('.')[0]+'.png';
if (UrlExists(src)) {
tile.getImage().src=src;
} else {
tile.getImage().src=errorTilePath;
}
} else {
tile.getImage().src=errorTilePath;
}
}
};
})());
function UrlExists(url){
try {
var http = new XMLHttpRequest();
http.open('HEAD', url, false);
http.send();
return http.status==200||http.status==403;
} catch(err){return false;}
}

i want to upload video from gallery in ios using titanium,Please guide me to solve this and upload the video successfully

// i have done the following code on the button click but when i
click on the choose button the screen gets stuck on this screen
only.
btnGallery.addEventListener('click', function() {
Ti.Media.openPhotoGallery({
mediaTypes : [![enter image description here][1]][1][Ti.Media.MEDIA_TYPE_VIDEO], *//to select video*
success : function(event) {
var result=event.media; *//Store video in blob form*
Ti.API.info(event);
var xhr = Titanium.Network.createHTTPClient();
xhr.onload = function(e) {
Ti.UI.createAlertDialog({
title : 'Success',
message : 'status code ' + this.status
}).show();
};
xhr.open('POST', 'http://videorequestlive.com/upload_videos');
xhr.send({video : event.media,uploadedby : Ti.App.Properties.getString('loginProfileId'),requested_video_description : rowChildren[1].text,requested_video_id : rowChildren[3].text,requestedby : rowChildren[4].text,requested_video_title : 'User',});
},
});
Your mediaTypes seems to be broken
Try this:
btnGallery.addEventListener('click', function() {
Ti.Media.openPhotoGallery({
mediaTypes : [Ti.Media.MEDIA_TYPE_VIDEO], *//to select video*
success : function(event) {
var result=event.media; *//Store video in blob form*
Ti.API.info(event);
var xhr = Titanium.Network.createHTTPClient();
xhr.onload = function(e) {
Ti.UI.createAlertDialog({
title : 'Success',
message : 'status code ' + this.status
}).show();
};
xhr.open('POST', 'http://videorequestlive.com/upload_videos');
xhr.send({video : event.media,uploadedby : Ti.App.Properties.getString('loginProfileId'),requested_video_description : rowChildren[1].text,requested_video_id : rowChildren[3].text,requestedby : rowChildren[4].text,requested_video_title : 'User',});
},
});