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
Related
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;`
I am having problems with Apache Cordova and Android. I have some code to send one picture to server, from an Android cellphone, but it doesn't work. I have tested the ajax and php code on the server, and it works, but when I try from the cellphone it does not.
app.js:
var pictureSource; // picture source
var destinationType; // sets the format of returned value
var image = "";
document.addEventListener("deviceready", onDeviceReady, false);
function onDeviceReady() {
pictureSource = navigator.camera.PictureSourceType;
destinationType = navigator.camera.DestinationType;
}
function capturePhoto() {
navigator.camera.getPicture(onPhotoDataSuccess, onFail, {
quality: 50,
destinationType: destinationType.DATA_URL
});
}
function onPhotoDataSuccess(imageData) {
var smallImage = document.getElementById('smallImage');
smallImage.style.display = 'block';
smallImage.src = "data:image/jpeg;base64," + imageData;
image = "data:image/jpeg;base64," + imageData;
}
function onFail(message) {
alert('Failed because: ' + message);
}
function submitFunction() {
var dataString = 'image='+encodeURIComponent(image);
$.ajax({
type: "POST",
url: "//192.0.1.2/testing/test.php",
data: dataString,
cache: false,
error: function(){
ShowStatus( "AJAX - error()" );
document.getElementById("result").innerHTML = 'Error';
},
beforeSend: function() {
document.getElementById("result").innerHTML = 'Enviando Data';
},
success: function(result){
document.getElementById("result").innerHTML = result;
}
});
}
test.php:
<?php
header('Access-Control-Allow-Origin: *');
require'connection.php';
$mysqli = conectarse();
$res = $mysqli->query("INSERT INTO imagenes (image) VALUES
('".$_POST['image']."')");
$mysqli->query($res);
if (!$res) {
printf("Errormessage: %sn", $mysqli->error);
}
?>
This code has the following dependencies:
cordova.js
jquery.min.js
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');
}
I am developing hybrid using phonegap 3.3. I am using camera plugin to capture image and store into photo album which working fine. Later, I have to read image file from the device storage.
I am using the following code.
window.requestFileSystem(LocalFileSystem.PERSISTENT, 0, gotFS, failFS);
function gotFS(fileSystem){
fileSystem.root.getFile(imageData, {create: true}, gotFileEntry, fail);
}
function gotFileEntry(){
fileEntry.file(gotFile,fail);
}
function gotFile(file){
alert(file.getParent().fullPath);
}
I am getting error in the first line. It is giving
FileError.ENCODING_ERR
I am not sure what I am doing wrong here. After, I have to move to another directory with new name. Could anyone help me to fix.
I am using camera plugin for capture images and file plugin to read files and directory.
--Sridhar
You can try with below code to capture and copy image
var pictureSource;
var destinationType;
var FileFolder = "";
var FileName = "";
var obj_imageCapture = {
capturePicture:function(imgFolder,imgName)
{
var image = imgFolder + imgName;
FileFolder = imgFolder;
FileName = imgName;
pictureSource = navigator.camera.PictureSourceType;
destinationType = navigator.camera.DestinationType;
navigator.camera.getPicture(obj_imageCapture.onPhotoDataSuccess1, obj_imageCapture.onFail, {quality: 50, destinationType: destinationType.FILE_URI , saveToPhotoAlbum: true });
},
onPhotoDataSuccess1:function(imageData){
obj_imageCapture.createFileEntry(imageData);
},
createFileEntry:function(imageURI) {
window.resolveLocalFileSystemURI(imageURI, obj_imageCapture.copyPhoto, obj_imageCapture.onFFail);
},
copyPhoto:function(fileEntry) {
try
{
var ext = fileEntry.fullPath.substr(fileEntry.fullPath.lastIndexOf('.'));
var imageN = "";
if(FileName.indexOf('.') > 0)
{
imageN = FileName.substr(0,FileName.lastIndexOf('.')) + ext;
}
else
{
imageN = FileName + ext;
}
window.requestFileSystem(LocalFileSystem.PERSISTENT, 0, function(fileSys) {
fileSys.root.getDirectory(FileFolder, {create: true, exclusive: false}, function(dir) {
fileEntry.copyTo(dir, imageN, obj_imageCapture.onCopySuccess, obj_imageCapture.onFFail);
}, obj_imageCapture.onFFail);
}, obj_imageCapture.onFFail);
}
catch(ex)
{
alert(ex.message);
}
},
onCopySuccess:function(entry) {
var smallimage = document.getElementById("myimage");
smallimage.style.display = "block";
smallimage.src = entry.fullPath + "?rand=" + Math.random();
},
onFFail:function(message)
{
alert("Error in photo : " + message.message);
}
};
Above code might helpful to you
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);
}
}