Phonegap Vue js Android uploading CAMERA image to API server - android

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;`

Related

Ionic: Getting Error Code 3 when uploading image using ng-cordova fileTransfer and Camera plugin

I am getting "Code 3" (connection refused) error when trying to upload an image file from my ionic app to remote server using FileTransfer plugin.
I used the camera plugin and have the captured image moved to permanent storage
$scope.selectPicture = function(sourceType) {
var options = {
quality: 75,
destinationType: Camera.DestinationType.FILE_URI,
sourceType: Camera.PictureSourceType.CAMERA,
allowEdit: true,
encodingType: Camera.EncodingType.JPEG,
popoverOptions: CameraPopoverOptions,
saveToPhotoAlbum: false,
correctOrientation:true
};
$cordovaCamera.getPicture(options).then(function(imagePath) {
var currentName = imagePath.replace(/^.*[\\\/]/, '');
//Create a new name for the photo
var d = new Date(),
n = d.getTime(),
newFileName = n + ".jpg";
localStorage.setItem('checklist',newFileName);
var namePath = imagePath.substr(0, imagePath.lastIndexOf('/') + 1);
// Move the file to permanent storage
$cordovaFile.moveFile(namePath, currentName, cordova.file.dataDirectory, newFileName).then(function(success){
$scope.image = newFileName;
localStorage.setItem('checklist',newFileName);
}, function(error){
$scope.showAlert('Error', error.exception);
});
}, function(err) {
// error
});
};
then I upload the image using the FileTransfer plugin
$scope.reportSending = function(){
$scope.report_no = localStorage.getItem('reportNumber');
$scope.imageLoc = localStorage.getItem('checklist');
var server = "http://localhost/api/api/public/api/sendreport",
filePath = cordova.file.dataDirectory + $scope.imageLoc;
var date = new Date();
var options = {
fileKey: "file",
fileName: $scope.imageLoc,
chunkedMode: false,
mimeType: "multipart/form-data",
params : {
report_no : $scope.report_no
}
};
$cordovaFileTransfer.upload(server, filePath, options).then(function(result) {
console.log(JSON.stringify(result.response));
}, function(err) {
console.log("ERROR: " + JSON.stringify(err));
//alert(JSON.stringify(err));
}, function (progress) {
// constant progress updates
});
};
when I execute the reportSending() function it returns an error it says:
ERROR: {"code":3,"source":"file:///data/user/0/com.ionicframework.appnew343084/files/1483519701226.jpg","target":"http://localhost/api/api/public/api/sendreport","http_status":null,"body":null,"exception":"Connection refused"}
it says "connection refused" in the exception but when I try the API in postman I can successfully upload a file.
So after searching tons of forums I found out that my problem was very simple..
changing the API url fixed the issue.
from
var server = "http://localhost/api/api/public/api/sendreport",
to
var server = "http://192.168.1.17/api/api/public/api/sendreport";
instead of using localhost I pointed the URL to my local server's IP
and I also noticed that I used comma , instead of semi-colon at the end of my variable declaration for the API.
now everything works as it should.

Phonegap Filetransfer works on iOS nothing happens on Android

Now, I have a problem with uploading some images on the server. My code works perfectly on iOS devices, but when I'm trying to upload on Android, it just doesn't do anything. Before the filetransfer, I'm trying to alert the ImageURI, but it's not happening as well.
I'm using PhoneGap Build with Phonegap version 3.4.0 and Sencha Touch 2.3. In the config.xml I use the core phonegap camera plugin: <gap:plugin name="org.apache.cordova.camera" />.
My fileupload script looks like this:
Ext.define('my_app.controller.Fileupload', {
extend: 'Ext.app.Controller',
requires: [
'Ext.MessageBox'
],
config: {
refs: {
fileupload: '#fileupload',
getLibraryImage: 'button[action=getLibraryImage]',
getCameraImage: 'button[action=getCameraImage]'
},
control: {
getLibraryImage: {
tap: 'getLibraryImage'
},
getCameraImage: {
tap: 'getCameraImage'
}
}
},
getLibraryImage: function() {
navigator.camera.getPicture(this.fileupload, onFail, {
destinationType: Camera.DestinationType.FILE_URI,
sourceType: Camera.PictureSourceType.PHOTOLIBRARY,
allowEdit: true,
targetWidth: 800,
targetHeight: 800
});
function onFail(message) {
alert('Failed because: ' + message);
}
},
getCameraImage: function() {
navigator.camera.getPicture(this.fileupload, onFail, {
destinationType: Camera.DestinationType.FILE_URI,
sourceType: Camera.PictureSourceType.CAMERA,
quality: 100,
allowEdit: true,
targetWidth: 800,
targetHeight: 800
});
function onFail(message) {
alert('Failed because: ' + message);
}
},
fileupload: function(imageURI) {
alert(imageURI);
Ext.Viewport.setMasked({
xtype: 'loadmask',
message: Loc.t('LOADMASK.FILEUPLOAD'),
styleHtmlContent: true,
indicator: true
});
var options = new FileUploadOptions();
options.fileKey = "file";
options.fileName = imageURI.substr(imageURI.lastIndexOf('/') + 1);
options.mimeType = "image/jpeg";
// if (Ext.os.is('Android')) {
// options.chunkedMode = true;
// }
var user = JSON.parse(localStorage.getItem('user'));
var user_id = user.id;
var username = user.username;
var params = new Object();
params.user_id = user_id;
params.username = username;
options.params = params;
var ft = new FileTransfer();
ft.upload(imageURI, encodeURI("my_upload_uri"), win, fail, options);
function win(response) {
if (Ext.JSON.decode(response.response).error) {
Ext.Viewport.setMasked(false);
Ext.Msg.alert('my_app', Ext.JSON.decode(response.response).error);
} else {
my_app.app.getController('Basic').ProfileImages();
Ext.Msg.alert('my_app', Ext.JSON.decode(response.response).success);
}
}
function fail(error) {
Ext.Viewport.setMasked(false);
alert("An error has occurred: Code = " + error.code);
}
}
});
If anyone can see the problem, I'd really appreciate the help! Thanks in advance.
My problem solved by upgrading to PhoneGap version 3.6.3.

Get the file name and the extension while uploading file in PhoneGap

I am uploding an image from a gallery using PhoneGap in Android but what I want to do is to fetch the file name and its extension which i am not be able to get it from imageuri so can any one tell me how can I find one
my imageURI is content://media/external/images/media/876 so is there a way to get a fileEntry by using this imageURI and read the file name and extension ?
function fileUpload(){
navigator.camera.getPicture(
uploadPhoto,
function(message) { alert('get picture failed'); },
{
quality : 50,
destinationType : navigator.camera.DestinationType.FILE_URI,
sourceType : navigator.camera.PictureSourceType.PHOTOLIBRARY
}
);
}
function uploadPhoto(imageURI) {
var options = new FileUploadOptions();
options.fileKey="uploaded_file";
alert(imageURI);
options.fileName=imageURI.substr(imageURI.lastIndexOf('/')+1);
options.mimeType="image/jpeg";
var params = new Object();
params.value1 = "test";
params.value2 = "param";
options.params = params;
var ft = new FileTransfer();
ft.upload(imageURI, encodeURI("http://www.mydomain.com/mobile_upload.php"), win, fail, options);
}
function win(r) {
alert("WIN" +r.response);
console.log("Code = " + r.responseCode);
console.log("Response = " + r.response);
console.log("Sent = " + r.bytesSent);
}
function fail(error) {
alert("error");
alert("An error has occurred: Code = " + error.code);
console.log("upload error source " + error.source);
console.log("upload error target " + error.target);
}
i found the answer and here is the code
window.resolveLocalFileSystemURI(imageURI, function(entry){
console.log("****************HERE YOU WILL GET THE NAME AND OTHER PROPERTIES***********************");
console.log(entry.name + " " +entry.fullPath);
}, function(e){
});
I had the same problem and think that I found a solution. I think it is not the best, but possible ;-)
After get File_URI from camera resolve File system from File_URI and in this fileEntry get file. This file (here filee) is a variable called type, this is the mime type of file.
function clickEvent() {
navigator.camera.getPicture(cameraSuccess, cameraError, {
destinationType: Camera.DestinationType.FILE_URI,
sourceType: Camera.PictureSourceType.SAVEDPHOTOALBUM
});
}
function cameraSuccess(file_URI) {
window.resolveLocalFileSystemURI(file_URI, function(fileEntry) {
fileEntry.file(function(filee) {
alert(filee.type); //THIS IS MIME TYPE
}, function() {
alert('error');
});
}, onError);
}
function onError() {
alert('fehler resolve file system');
}
function cameraError() {
alert('fehler');
}

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

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);
}
}

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