android - phonegap file uploader plugin with progress bar in status bar - android

Anyone know a phonegap file uploader plugin with progress bar in status bar. I found one here https://github.com/phonegap/phonegap-plugins/tree/master/Android/FileUploader but no progress bar and maybe it outdated (2 years ago). Anyone help?

Well, as far as I know that's the only one.
I just tried it and it doesn't work very well.
The file gets uploaded but for some reason you first get a quickly increasing progress indication. Once that reaches 100% the file is actually starting to get uploaded and you still need to wait a lot of time without any indication of progress.

it may be too late for the answer, but with the plugin file attached to the plugin dialogs you will be able to display the native progress.
The code example follows.
Cheers
function onSuccess(r) {
navigator.notification.progressStop();
console.log('success');
}
function onError(error) {
navigator.notification.progressStop();
}
var upload = function (imageURI) {
navigator.notification.progressStart('', 'Uploading image...');
var fileURL = imageURI;
var uri = encodeURI(server + "uploadPacientes.php");
var codigo = Math.floor(Math.random() * 655365456342524252);
var paciente = document.getElementById('paciente_nome');
var options = new FileUploadOptions();
options.fileKey = "file";
options.fileName = paciente + codigo + ".jpg";
options.mimeType = "image/jpg";
var headers = {
'headerParam': 'headerValue'
}
options.headers = headers;
var ft = new FileTransfer();
ft.onprogress = function (progressEvent) {
if (progressEvent.lengthComputable) {
var percentual = Math.floor(progressEvent.loaded / progressEvent.total *
100);
navigator.notification.progressValue(percentual);
} else {
navigator.notification.progressValue('0');
}
}
ft.upload(fileURL, uri, onSuccess, onError, options);
}

I reply late, but I hope it helps someone in the future! Cheers
function salvarARQUIVOS(superFILE) {
var tipoArquivo = $( "input[name=tipoArquivo]:checked" ).val();
var dataArquivo = $('#dataArquivo').val();
var arquivoFile = superFILE;
$('#btnARQUIVO').html('ENVIANDO');
if (dataArquivo === "") {
$('#btnARQUIVO').html('SALVAR');
aviso('Informe a data do arquivo');
return true;
}
var extensao = arquivoFile.substr(arquivoFile.lastIndexOf('.') + 1);
if (extensao != "pdf") {
aviso('Somente arquivos em pdf');
return true;
}
myApp.showIndicator();
var arq = arquivoFile.substr(arquivoFile.lastIndexOf('/') + 1);
arq = arq.replace(/[\W_]/g, "-");
var uri = encodeURI(serv + "uploadPDF.php");
var nome_arquivo = arq.replace('-pdf', '.pdf');
console.log('nome_arquivo = > ' + nome_arquivo);
var options = new FileUploadOptions();
options.fileKey = "file";
options.fileName = nome_arquivo;
options.mimeType = "application/pdf";
options.chunkedMode = false;
var headers = {
'headerParam': 'headerValue'
};
options.headers = headers;
var ft = new FileTransfer();
ft.upload(arquivoFile, uri, onSuccessoArquivo, onErrorArquivo, options);
function onSuccessoArquivo(r) {
myApp.hideIndicator();
linkArquivo = 'arquivosExames/' + nome_arquivo;
idPaciente = $('#idPaciente').val();
String = 'idPaciente=' + idPaciente + '&tipoArquivo=' + tipoArquivo + '&dataArquivo=' + dataArquivo + '&linkArquivo=' + linkArquivo;
console.log(String);
$.ajax({
url: serv + "saveServ.php",
type: "GET",
data: String,
dataType: "json",
cache: false,
success: function (data) {
$('#btnARQUIVO').html('SALVAR');
myApp.hideIndicator();
changePage('pagelistaarquivos');
aviso('Enviado');
}
});
}
function onErrorArquivo(error) {
myApp.hideIndicator();
$('#btnARQUIVO').html('SALVAR');
aviso('Erro ao enviar o arquivo ' + error.code);
}
}

Related

Phonegap Vue js Android uploading CAMERA image to API server

I'm trying to upload picture taken by Android Camera (cordova-plugin-camera). My code for that is
takePicture () {
navigator.camera.getPicture(result => {
this.newUnit.addedPic = true
this.newUnit.image = result
}, error => {
alert(error);
},
{
sourceType : Camera.PictureSourceType.CAMERA,
destinationType: Camera.DestinationType.FILE_URI,
encodingType: Camera.EncodingType.JPEG,
});
},
In my this.newUnit.addedPic I got the path like:
file:///storage/emulated/0/Android/data/.../1234.jpg
How can I use it to upload the picture to server from mobile app?
In my web part I use FormData to upload the picture.
I was trying to do it by FileTransfer but I get error code 1:
let win = r => {alert(`win`)}
let fail = error => {
alert("An error has occurred: Code = " + error.code);
console.log("upload error source " + error.source);
console.log("upload error target " + error.target);
}
var options = new FileUploadOptions();
options.fileKey = "file";
options.fileName = this.newUnit.image.substr(this.newUnit.image.lastIndexOf('/') + 1);
options.mimeType = "image/jpeg";
var params = {};
params.name = "test";
params.creator = 3;
options.params = params;
var ft = new FileTransfer();
ft.upload(this.newUnit.image, encodeURI("http://myserver/api/v0/units/"), win, fail, options);
SOLVED. The problem was because of empty headers and http method.
var headers = { 'Authorization':`Token ${token}` };
options.headers = headers;
options.httpMethod= "POST";
options.chunkedMode = true;`

Broken image being displayed when using the image path returned from cordovacapture captureimage

I have tried various solutions: $cordovaCapture, $cordovaCamera(DATA_URL can display the picture, but i want file_URI to do the same).
here is my code snippet:
$scope.addImage = function() {
var options = {limit: 1};
$cordovaCapture.captureImage(options).then(function(imageData) {
console.log(imageData);
// var jsonobj=angular.toJson(imageData);
$scope.profile.image = imageData[0];
console.log(angular.toJson(imageData));
console.log($scope.profile.image.localURL);//the path to upload
document.getElementById('myImage').src = "'"+$scope.profile.image.localURL+"'";//have already tried without the quottes
/* window.plugins.Base64.encodeFile($scope.profile.image.localURL,function(base64){ // Encode URI to Base64 needed for contacts plugin
$scope.profile.image.preview = base64;
console.log($scope.profile.image.preview);
});*/
// Success! Image data is here
}, function(err) {
});
i even tried whitelisting certainties in the module as in :
.config( [
'$compileProvider',
function( $compileProvider )
{
$compileProvider.imgSrcSanitizationWhitelist(/^\s*(https?|file|content|blob|cdvfile):|data:image\//);
}
])
It didn't help either. I am testing the project in both device and emulator. I even tried base64 encoding the file from the path. Nothing works as to display the recently taken picture. The path that i retrieve is like this:
cdvfile://localhost/persistent/DCIM/Camera/123123123.jpg
Instead of using file_URI to upload the image. I used data_URL,converted the image to blob and used the cordova-file-transfer plugin to upload the file to the server. In that way, i could use the base64 encoded image on the html side as well as upload at the same time.
$scope.captureImage = function() {
navigator.camera.getPicture(cameraSuccess, cameraError, {
destinationType: Camera.DestinationType.DATA_URL,
correctOrientation: true
});
}
var cameraSuccess = function(imageData) {
$scope.profileImageSource = imageData;
$scope.changeImage = function(base64Data, contentType) {
contentType = contentType || '';
var sliceSize = 512;
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
});
}
$scope.picture = $scope.changeImage(imageData, 'image/png');
$scope.$digest();
}
HTML:
<img ng-src="data:image/gif;base64,{{profileImageSource}}">

Phonegap fileTransfer.Download is not working on ios phonegap 3.0

I am developing an app with JQM and then using build.phonegap.com, i am building the app.
I have a feature to download the audio file from the server and then play it in the app.
it is working perfectly in android.
I tried all possibilities to make it work.
can some one help on this.
here is my complete file handling code
fileSystem.root.getDirectory("auidofiles", {
create : true,
exclusive : false
}, function(dirEntry) {
dirEntry.getFile(mp3_file, {
create : false,
exclusive : false
}, function(fileEntry) {
alert("File Already downloaded");
if (device.platform == "Android") {
FILEPATH = fileEntry.fullPath;
//FILEPATH = fileEntry.toURI();
playAudio();
} else {
var filePathLocal1 = getPhoneGapPath() + "auidofiles/" + mp3_file;
//var filePathLocal = fileSystem.root.toURL() + "auidofiles/" + mp3_file;
//alert("Ios File Path:" + filePathLocal);
//FILEPATH = filePathLocal;
//FILEPATH = fileEntry.fullPath;
//FILEPATH = fileEntry.toURI();
playAudio();
}
}, function(fileFail) {
alert("File Not found");
var ft = new FileTransfer();
ft.onprogress = function(progressEvent) {
if (progressEvent.lengthComputable) {
var perc = Math.floor(progressEvent.loaded
/ progressEvent.total * 100);
$('#downloadStatus').html(perc + "% loaded...");
} else {
if ($('#downloadStatus').html() == "") {
$('#downloadStatus').html("Loading");
} else {
$('#downloadStatus').html(
$('#downloadStatus').html() + ".");
}
}
}; //ft.Progress
var filePathLocal = fileSystem.root.toURL() + "auidofiles/" + mp3_file;
ft.download(audioStreamUrl, filePathLocal, function(entry) {
//alert("File = " + entry.toURI());
if (device.platform == "Android") {
FILEPATH = entry.fullPath;
//FILEPATH = entry.toURI();
playAudio();
} else {
var filePathLocal1 = getPhoneGapPath() + "auidofiles/" + mp3_file;
//alert("Ios File Path:" + filePathLocal);
FILEPATH = filePathLocal;
//FILEPATH = entry.fullPath;
//FILEPATH = entry.toURI();
playAudio();
}
}, function(error) {
$('#downloadStatus').html(
"download error source " + error.source);
$('#downloadStatus').html(
"download error target " + error.target);
$('#downloadStatus').html("upload error code" + error.code);
}); //ft.Download
}); //getFile End
}, function(dirfail) {
alert("dirfail");
alert(JSON.stringify(dirfail))
$('#downloadStatus').html(JSON.stringify(dirfail));
})
function getPhoneGapPath() {
var path = window.location.pathname;
path = path.substr( 0, path.length - 10 );
return 'file://' + path;
};
There is a new requirement to use .toURL() instead of .fullPath
This fixes the majority of these type of problems - however I have experienced a similar problem using older versions of the iOS (5.x) where filetransfer.download never fires success/fail/progress events even though it does actually download the file. I then get an app crash when I try to restart the app...
I had the same issue and fixed it with downgrading the Cordova Plugin FileTransfer from v0.4.2 to v0.3.3 while using Phonegap/Cordova v3.3.

How to upload FILE_URI using Google Drive API: Insert File

On Android, I'm trying to upload the output from Cordova/Phonegap getPicture() using Google Drive API: Insert File. Is there a way to do this using the FILE_URI instead of DATA_URL (base64)?
I tried Camera.DestinationType.DATA_URL first, but it didn't return Base64 data like it was supposed to, it just returned the same thing as FILE_URI. So now I'm trying to figure out how to pass FILE_URI to Google Drive Insert File (which takes Base64). Is there a way to convert FILE_URI to Base64?
Cordova code:
navigator.camera.getPicture(onSuccess, onFail,
{ quality: 50, destinationType: Camera.DestinationType.FILE_URI });
function onSuccess(imageURI) {
var image = document.getElementById('myImage');
image.src = imageURI;
// need to do something like this:
var fileData = ConvertToBase64(imageURI);
insertFile(fileData);
}
Google Drive code:
/**
* Insert new file.
*
* #param {File} fileData File object to read data from.
* #param {Function} callback Function to call when the request is complete.
*/
function insertFile(fileData, callback) {
const boundary = '-------314159265358979323846';
const delimiter = "\r\n--" + boundary + "\r\n";
const close_delim = "\r\n--" + boundary + "--";
var reader = new FileReader();
reader.readAsBinaryString(fileData);
reader.onload = function(e) {
var contentType = fileData.type || 'application/octet-stream';
var metadata = {
'title': fileData.fileName,
'mimeType': contentType
};
var base64Data = btoa(reader.result);
var multipartRequestBody =
delimiter +
'Content-Type: application/json\r\n\r\n' +
JSON.stringify(metadata) +
delimiter +
'Content-Type: ' + contentType + '\r\n' +
'Content-Transfer-Encoding: base64\r\n' +
'\r\n' +
base64Data +
close_delim;
var request = gapi.client.request({
'path': '/upload/drive/v2/files',
'method': 'POST',
'params': {'uploadType': 'multipart'},
'headers': {
'Content-Type': 'multipart/mixed; boundary="' + boundary + '"'
},
'body': multipartRequestBody});
if (!callback) {
callback = function(file) {
console.log(file)
};
}
request.execute(callback);
}
}
I realize this is a bit old - but it now looks like you can use a FileReader in phoneGap.
I haven't tested this yet, but something like this should also work, without the canvas hack.
[EDIT - tested and revised the code below. works for me :D ]
var cfn = function(x) { console.log(x) };
var cameraOps = { quality: 50, destinationType: Camera.DestinationType.FILE_URI };
navigator.camera.getPicture(function(imagePath) {
window.resolveLocalFileSystemURL(imagePath, function(fileEntry) {
fileEntry.file(function (file) {
var reader = new FileReader();
reader.onloadend = function(evt) {
console.log("read success!!!");
console.log(evt.target.result);
};
reader.readAsDataURL(file);
}, cfn);
}, cfn);
}, cfn);
Yes you can....
Specify Destination Type as FILE_URI itself and in imagedata you will be getting the images file uri place it in a image tag and then place it inside HTML5 canvas and canvas has one method called toDataURL where you will be able to get the base64 of the corresponding image.
function onSuccess(imageData)
{
var $img = $('<img/>');
$img.attr('src', imageData);
$img.css({position: 'absolute', left: '0px', top: '-999999em', maxWidth: 'none', width: 'auto', height: 'auto'});
$img.bind('load', function()
{
var canvas = document.createElement("canvas");
canvas.width = $img.width();
canvas.height = $img.height();
var ctx = canvas.getContext('2d');
ctx.drawImage($img[0], 0, 0);
var dataUri = canvas.toDataURL('image/png');
});
$img.bind('error', function()
{
console.log('Couldnt convert photo to data URI');
});
}
Thanks to Arun for pointing me in the right direction. I ended up using this javascript function, which was based off http://jsfiddle.net/jasdeepkhalsa/L5HmW/
function getBase64Image(imgElem) {
// imgElem must be on the same server otherwise a cross-origin error will be thrown "SECURITY_ERR: DOM Exception 18"
var canvas = document.createElement("canvas");
canvas.width = imgElem.clientWidth;
canvas.height = imgElem.clientHeight;
var ctx = canvas.getContext("2d");
ctx.drawImage(imgElem, 0, 0);
var dataURL = canvas.toDataURL("image/jpeg");
dataURL = dataURL.replace(/^data:image\/(png|jpg|jpeg);base64,/, "");
return dataURL;
}

Phonegap Filetransfer API Not Work in SGS SII

i'm newbie on phonegap, I am just trying transfer a file to my server via phonegap 1.0 Filetransfer API and work on android emulator Android 2.3.3 (API level 10) but don't work with real device ( samsung galaxy sII) bellow my code :
document.addEventListener("deviceready",onDeviceReady,false);
function onDeviceReady() {
pictureSource=navigator.camera.PictureSourceType;
destinationType=navigator.camera.DestinationType;
}
function capturePhoto() {
navigator.camera.getPicture(onPhotoDataSuccess, onFail, {
quality: 30, destinationType: destinationType.FILE_URI
});
}
function onPhotoURISuccess(imageURI) {
$(".loading").show()
var doit = $('a#sendkamera').attr('rel');
var smallImage = document.getElementById('smallImage');
smallImage.style.display = 'block';
smallImage.src = imageURI;
var options = new FileUploadOptions();
options.fileKey="file";
//options.fileName="newfile.txt";
options.mimeType="image/jpeg";
var params = new Object();
params.value1 = "test";
params.value2 = "param";
options.params = params;
var ft = new FileTransfer();
ft.upload(imageURI, "http://api.byur.in/android/upload/", win, fail, options);
}
function win(r) {
console.log("Code = " + r.responseCode);
console.log("Response = " + r.response);
console.log("Sent = " + r.bytesSent);
alert("Code = " + r.responseCode);
alert("Response = " + r.response);
alert("Sent = " + r.bytesSent);
alert("Sukses");
$(".loading").hide()
}
function fail(error) {
alert("An error has occurred: Code = " = error.code);
}
I don't understand, why this code can be successful with alert status code = -1, but when I look at the log server, I don't see the request.
i try upload file via ajax and work on emulator but dont work with real device with error message status code = 0. bellow my code
function capturePhoto() {
navigator.camera.getPicture(onPhotoDataSuccess, onFail, { quality: 30 });
}
function errorCallback(xhr, textStatus, errorThrown) {
navigator.notification.beep(3);
alert(textStatus + errorThrown + ' coba lagi di waktu mendatang');
alert(xhr.responseText);
}
function successIMG(imageData) {
var doit = $('a#sendkamera').attr('rel');
$('.loading').show();
var data = {image: imageData};
var url = 'http://api.byur.in'+doit;
$.ajax({url:url, type:'POST', data:data, success:function(data){
$('.loading').hide(); alert('sukses'); },error: errorCallback });
}
I am not sure where I am going wrong. What can I do to fix this problem?
thanks for your reply

Categories

Resources