Save and open pdf (Javascript-Cordova-Android) - javascript

I´m trying to save a pdf (generated with jspdf) and then open, just 2 buttons, but nothing happens on device and on console no error is shown.
This is the code to save:
window.resolveLocalFileSystemURL(cordova.file.externalDataDirectory, function(dir) {
dir.getFile("cotizacion.pdf", {create: true, exclusive: false}, function (fileEntry) {
fileEntry.createWriter(function (writer) {
writer.onwrite = function(evt) {
console.log("Escritura exitosa");
};
console.log("Escribiendo...");
writer.write(window.cotizacion);
})
},function () {
console.log("Error al guardar");
});
});
And this is to open:
window.resolveLocalFileSystemURL(cordova.file.externalDataDirectory, function(dir) {
dir.getFile(filename, {create:false}, function(fileEntry) { //EXISTS
var url = "file:/" + cordova.file.externalDataDirectory + "/cotizacion.pdf";
window.open(url, '_system');
}, function() {
//NOT EXISTS
alert('Hubo un problema al recuperar la cotización');
});
});
What can I do to make it work?
Thank you all.
PS: I have all the plugins File, FileTransfer, InAppBrowser

Related

Sapui5 ODATA Busy Indicator Dialog don't show [duplicate]

This question already has answers here:
Busy Dialog not showing during server requests
(2 answers)
Closed 1 year ago.
I have an issue with my code, i need to show a busy dialog when i click on "save", but it doesn't show i don't know why, i searched for 5 days and nothing helped me, i tried with async post, with delayed call and other things to make this work.
On the image when i click on the button "Guardar", after that i need to show a busy dialog when the comunication to the server starts, the code what i have is the next:
onSaveRaw: function(oEvent) {
var that = this;
var ILgort = this.byId("sAlmacen_id").getValue();
var IWerks = this.byId("sCentro_id").getValue();
var IFechaoper = this.byId("sDate_id").getValue();
var RecTemm = this.byId("sTemm_id").getValue();
var RecTemt = this.byId("sTemt_id").getValue();
var RecDeno = this.byId("sDeno_id").getValue();
var RecPorc = this.byId("sPorc_id").getValue();
var RecPres = this.byId("sPres_id").getValue();
var RecHume = this.getView().byId("_select0").getSelectedKey();
var RecAgua = this.getView().byId("_select1").getSelectedKey();
if (this.validarCampoRequerido(ILgort)) {
return;
}
if (this.validarCampoRequerido(IWerks)) {
return;
}
if (this.validarCampoRequerido(IFechaoper)) {
return;
}
if (this.validarCampoRequerido(RecTemm)) {
return;
}
if (this.validarCampoRequerido(RecTemt)) {
return;
}
if (this.validarCampoRequerido(RecDeno)) {
return;
}
if (this.validarCampoRequerido(RecPorc)) {
return;
}
if (this.validarCampoRequerido(RecPres)) {
return;
}
//Creación del catalogo de datos del formulario.
var dialog = new sap.m.Dialog({
title: "Confirmación",
type: "Message",
state: "Warning",
content: new sap.m.Text({
text: "Se generará el documento de inventario. ¿Desea continuar?"
}),
beginButton: new sap.m.Button({
text: "Guardar",
press: function() {
var oData = {
"ILgort": ILgort,
"IWerks": IWerks,
"IFechainv": IFechaoper,
"ICharact010": RecTemm,
"ICharact020": RecTemt,
"ICharact030": RecDeno,
"ICharact040": RecPorc,
"ICharact050": RecPres,
"ICharact080": RecHume,
"ICharact090": RecAgua
};
//console.log(oData);var _this = this;
//Se crea instancia del servicio
var oModel = new sap.ui.model.odata.ODataModel("/sap/opu/odata/sap/XXXXXXXXX/");
var oGlobalBusyDialog = new sap.m.BusyDialog();
oGlobalBusyDialog.open();
oModel.create("/LECTURATANQUESet", oData, null, function(oResponse) {
sap.m.MessageBox.alert(oResponse.Message, {
title: "Exito",
textDirection: sap.ui.core.TextDirection.Inherit,
onClose: function() {
that.onRefresh();
that._navBack();
}
});
}, function(oError) {
var oNum = oError.response.statusCode;
if (oNum == "500") {
sap.m.MessageBox.alert("Error, Sesión Finalizada por tiempo de Conexión.", {
title: "Error",
textDirection: sap.ui.core.TextDirection.Inherit,
onClose: function() {}
});
} else if (oNum == "504") {
sap.m.MessageBox.alert("Error de gateway, vuelva a intentar por favor.", {
title: "Error",
textDirection: sap.ui.core.TextDirection.Inherit,
onClose: function() {}
});
} else {
var oMsg = $(oError.response.body).find("message").first().text();
sap.m.MessageBox.alert(oMsg, {
title: "Error",
textDirection: sap.ui.core.TextDirection.Inherit,
onClose: function() {}
});
}
});
oGlobalBusyDialog.close();
dialog.close();
}
}),
endButton: new sap.m.Button({
text: "Cancelar",
press: function() {
dialog.close();
}
}),
afterClose: function() {
}
});
dialog.open();
}
If someone can give me any tip I'll be very greatful.
You are using wrong BusyIndicator. Try this out:
sap.ui.define([
"sap/ui/core/BusyIndicator"
],
function (BusyIndicator) {
BusyIndicator.show();
//...
BusyIndicator.hide();
});
You need to call oGlobalBusyDialog.close(); inside the success and error callbacks of the create function. So, when ever the create function completes (either a success or error) you will close the busy dialog.
Also, you've to delete the oGlobalBusyDialog.close(); in the second last line of the press event handler.
EDIT (Updating how to use create, after re-reading the docs)
Use create like this
oModel.create("/LECTURATANQUESet",
oData, {
success: successCallback,
error: errorCallbak
}
)
I get this problem recently also. The Create function of sap.ui.model.odata.ODataModel, when executed (synchronously), freezes the browser and prevents the slower busy indicator from showing.
I solved it by activating the async mode of the function (it is executed synchronously by default):
oModel.create("/LECTURATANQUESet",
oData, {
success: successCallback,
error: errorCallbak,
async: true
}
https://sapui5.hana.ondemand.com/sdk/#/api/sap.ui.model.odata.ODataModel%23methods/Summary
However, this should be done with some considerations: "Whether the request should be done asynchronously. Default: false Please be advised that this feature is officially unsupported as using asynchronous requests can lead to data inconsistencies if the application does not make sure that the request was completed before continuing to work with the data."
Just add the solution here to somebody that needs xD!

Mistake from cordova.js after getting file from camera

We got file, it lies in cache, and i see it in Console
But when i tried to save it and send, i got this mistakes from cordova.js
Wrong type for parameter "newName" of Entry.copyTo: Expected String, but got Number.
Uncaught TypeError: Wrong type for parameter "newName" of Entry.copyTo: Expected String, but got Number.
Error in Success callbackId: File1917405046 : TypeError: Wrong type for parameter "newName" of Entry.copyTo: Expected String, but got Number.
ngCordova installed and injected
Cordova is updated
and i can't send my file, please help me
that's my code in controller
$scope.attachPhoto = function() {
$ionicActionSheet.show({
buttons: [
{ text: '<i class="icon ion-android-image"></i>Перейти в галерею' },
{ text: '<i class="icon ion-android-camera"></i> Сделать фото' }
],
cancelText: 'Cancel',
cancel: function() {
},
buttonClicked: function(index) {
var options = {
destinationType : Camera.DestinationType.FILE_URI,
sourceType : Camera.PictureSourceType.CAMERA,
allowEdit : false,
encodingType: Camera.EncodingType.JPEG,
popoverOptions: CameraPopoverOptions
};
$cordovaCamera.getPicture(options).then(function(imageData) {
onImageSuccess(imageData);
console.log(imageData);
function onImageSuccess(fileURI) {
createFileEntry(fileURI);
console.log(fileURI);
}
function createFileEntry(fileURI) {
window.resolveLocalFileSystemURL(fileURI, copyFile, fail);
console.log(fileURI);
}
function copyFile(fileEntry) {
fileEntry.file(function(file) {
var reader = new FileReader();
reader.onloadend = function(e) {
var imgBlob = new Blob([ this.result ], { type: "image/jpeg" } );
$scope.attach = true;
$scope.file = imgBlob;
};
reader.readAsArrayBuffer(file);
});
window.resolveLocalFileSystemURL(cordova.file.dataDirectory, function(fileSystem2) {
fileEntry.copyTo(
fileSystem2,
12345,
onCopySuccess,
fail
);
}, fail);
}
function onCopySuccess(entry) {
$scope.$apply(function () {
$scope.images.push(entry.nativeURL);
$scope.attach = true;
$scope.sendPhoto();
});
}
function fail(error) {
console.log("fail: " + error.code);
}
}, function(err) {
console.log(err);
});
console.log(options);
return true;
}
})
};
$scope.sendPhoto = function() {
var data = {
file: $scope.file
}
console.log(data);
var fd = new FormData(data);
xhr = new XMLHttpRequest();
xhr.open("POST", "http://eatmeet.ru/serv.php");
xhr.setRequestHeader('Content-Type', 'application/upload');
xhr.send(fd);
}
Try to parse a string as fileName, not a number. Please check the file documentation.
The correct syntax is:
fileEntry.copyTo(parent [DirectoryEntry], newName [DOMString], successCallback [Function], errorCallback [Function]);
window.resolveLocalFileSystemURL(cordova.file.dataDirectory, function(fileSystem2) {
fileEntry.copyTo(
fileSystem2,
"12345",
onCopySuccess,
fail
);
}, fail);

Cordova File API saving file to memory card

Firstly why in gods name is there no tutorial for this even Cordova's guides don't tell you how to save a flaming file to a location on the phone.
(function(w){
function FileServices(FileName, callb){
var self = this;
var isFileOpen = false;
var fileHandler;
// open file handle
function OpenFile(callb){
window.requestFileSystem(LocalFileSystem.PERSISTENT, 5*1024, function (fs) {
fs.root.getFile(cordova.file.externalDataDirectory+FileName, { create: true, exclusive: false }, function (fileEntry) {
fileHandler = fileEntry;
isFileOpen = true;
callb(self, fileHandler);
});
}, function(e,c){console.log(e,c);});
}
// write to file
function WriteFile(fileEntry, dataObj, isAppend, callback) {
// Create a FileWriter object for our FileEntry (log.txt).
fileEntry.createWriter(function (fileWriter) {
fileWriter.onerror = function (e) {
};
// If we are appending data to file, go to the end of the file.
if (isAppend) {
try {
fileWriter.seek(fileWriter.length);
}
catch (e) { }
}
fileWriter.write(dataObj);
callback(self, fileWriter);
});
}
this.writeLine = function(txt, append, callback){
if(isFileOpen){
WriteFile(fileHandler, new Blob([txt], { data:'plain/text' }), append, callback);
}
}
OpenFile(callb);
};
// add to the navigator when device ready
document.addEventListener("deviceready", function(){
navigator.FileServices = function GetFileServices(FileName, callback){
return new FileServices(FileName, callback);
}
});
})(window);
All i get is "Error Code 5 = FileError.ENCODING_ERR";
I can't work it out....

Phonegap (Cordova) doesn't write file to Android

I'm having a frustrating issue getting cordova to write files to Android devices.
According to the log, everything is firing correctly and the plugin methods are responding with successes etc, but when I go searching for the files they're no where to be found.
Currently I'm just using a fresh phonegap test application and I followed the following guide and used their example code verbatim. The plugins are installed according to the logs are executing.
http://docs.phonegap.com/en/edge/cordova_file_file.md.html
I'm expecting the file to show up in /android/data/com.testapp.myapp/files
This is my test code:
var app = {
// Application Constructor
initialize: function() {
this.bindEvents();
},
// Bind Event Listeners
//
// Bind any events that are required on startup. Common events are:
// 'load', 'deviceready', 'offline', and 'online'.
bindEvents: function() {
document.addEventListener('deviceready', this.onDeviceReady, false);
},
// deviceready Event Handler
//
// The scope of 'this' is the event. In order to call the 'receivedEvent'
// function, we must explicitly call 'app.receivedEvent(...);'
onDeviceReady: function() {
app.receivedEvent('deviceready');
window.requestFileSystem(LocalFileSystem.PERSISTENT, 0, app.gotFS, app.fail);
},
// Update DOM on a Received Event
receivedEvent: function(id) {
var parentElement = document.getElementById(id);
var listeningElement = parentElement.querySelector('.listening');
var receivedElement = parentElement.querySelector('.received');
listeningElement.setAttribute('style', 'display:none;');
receivedElement.setAttribute('style', 'display:block;');
console.log('Received Event: ' + id);
},
gotFS: function(fileSystem) {
fileSystem.root.getFile("testFile.txt", {create: true, exclusive: false}, app.gotFileEntry, app.fail);
},
gotFileEntry: function(fileEntry) {
fileEntry.createWriter(app.gotFileWriter, app.fail);
},
gotFileWriter: function(writer) {
writer.onwriteend = function(evt) {
console.log("contents of file now 'some sample text'");
writer.truncate(11);
writer.onwriteend = function(evt) {
console.log("contents of file now 'some sample'");
writer.seek(4);
writer.write(" different text");
writer.onwriteend = function(evt){
console.log("contents of file now 'some different text'");
}
};
};
writer.write("some sample text");
},
fail: function() {
alert("failed");
}
};
And here are the log entries from the logCat showing it firing off:
09-26 07:24:37.991 I/chromium( 2027): [INFO:CONSOLE(49)] "Received
Event: deviceready", source: file:///android_asset/www/js/index.js (49)
09-26 07:24:38.591 D/TEST ( 2027): cdvfile://localhost/persistent/testFile.txt: 16
09-26 07:24:39.063 I/chromium( 2027): [INFO:CONSOLE(62)] "contents of file now 'some sample text'", source: file:///android_asset/www/js/index.js (62)
09-26 07:24:39.075 D/TEST ( 2027): cdvfile://localhost/persistent/testFile.txt: 15
09-26 07:24:39.155 I/chromium( 2027): [INFO:CONSOLE(65)] "contents of file now 'some sample'", source: file:///android_asset/www/js/index.js (65)
09-26 07:24:39.363 I/chromium( 2027): [INFO:CONSOLE(69)] "contents of file now 'some different text'", source: file:///android_asset/www/js/index.js (69)
Any insight to why this maybe happening would be great.
Thanks!
Don't make it so complex dude , it's a code snipest to write data to file . data which stored in 'decdata' variable . Don't forget to change 'somefolder' for folder in root directory and 'datafilename' the file which data is stored.
Also you should add file plugin .
function start(){
window.requestFileSystem(LocalFileSystem.PERSISTENT, 0, writedata, fail);
}
var decdata;
function writedata(fileSystem) {
fileSystem.root.getDirectory("<<somefolder>>", { create: true }, gotDir);
}
function gotDir(dirEntry) {
dirEntry.getFile(<<datafilename>>, { create: true, exclusive: false }, gotFile);
}
function gotFile(fileEntry) {
fileEntry.createWriter(gotFileWriter, fail);
}
function gotFileWriter(writer) {
writer.onwriteend = function (evt) {
writer.truncate(1);
writer.onwriteend = function (evt) {
writer.seek(0);
writer.write(decdata);
writer.onwriteend = function (evt) {
}
};
};
writer.write("some sample text");
}
function fail(error) {
alert('error' + error.code);
}

Meteor file upload not working

I'm trying to upload images via Meteors CollectionFS but I'm not getting any errors in the client side code so I'm not sure what's broken. I see the console.log message "inside upload" but I don't see any success or fail messages from the Images.insert callback. Help.
myproject/client/upload.html
<template name="upload">
<form>
<input class="upload" type="file" id="upload" name=".../">
</form>
</template>
myproject/client/upload.js
Template.providerblock.events({
'click .upload': function(event, template) {
event.preventDefault();
var photo = $('#upload')[0];
var file = photo.files[0];
console.log("inside upload");
Images.insert(file, function (err, fileObj) {
if(err) {
console.log("unable to upload file");
} else {
console.log("file upload success");
}
});
},
});
myproject/lib/images.js
var Images = new FS.Collection("images", {
stores: [new FS.Store.FileSystem("images", {path: "~/uploads"})]
});
Images.allow({
insert: function() {
return true;
},
update: function() {
return true;
},
remove: function() {
return true;
},
download: function() {
return true;
}
});
You should:
Use 'change .upload': instead of 'click .upload':.
Images instead of var Images so you can use the variable in other file.

Categories

Resources