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');
}
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 have uploaded vcf file successfully on server on getting help from my previous question (the one which is edited)
Now I need a help in how to read that vcf file or vcard from server and display as a contact number and contact name in my phonegap app.
plugin used cordova-plugin-file-transfer
Can anyone help on this ?
Using plugin cordova-plugin-file-transfer https://github.com/apache/cordova-plugin-file-transfer you can download file from server.
For Read vcf file, you need https://github.com/nilclass/vcardjs JavaScript based library. you can directly use .js files.
You can follow below example.
window.requestFileSystem(window.TEMPORARY, 1 * 1024 * 1024, function (fs) {
console.log('file system open: ' + fs.name);
var fileName = "temp.vcf";
var dirEntry = fs.root;
dirEntry.getFile(fileName, { create: true, exclusive: false }, function (fileEntry) {
download(fileEntry,"server-path-to-file.vcf");
}, onErrorCreateFile);
}, onErrorLoadFs);
function download(fileEntry, uri) {
var fileTransfer = new FileTransfer();
var fileURL = fileEntry.toURL();
fileTransfer.download(
uri,
fileURL,
function (entry) {
console.log("Successful download...");
console.log("download complete: " + entry.toURL());
readFile(entry);
},
function (error) {
console.log("download error source " + error.source);
console.log("download error target " + error.target);
console.log("upload error code" + error.code);
},
null, // or, pass false
{
//headers: {
// "Authorization": "Basic dGVzdHVzZXJuYW1lOnRlc3RwYXNzd29yZA=="
//}
}
);
}
function readFile(fileEntry) {
fileEntry.file(function (file) {
var reader = new FileReader();
reader.onloadend = function () {
console.log("Successful file read: " + reader.result);
reader.parseVCard(reader.result);
};
reader.readAsText(file);
}, onErrorReadFile);
}
function parseVCard(vCarddata){
VCF.parse(vCarddata, function(vcard) {
// this function is called with a VCard instance.
// If the input contains more than one vCard, it is called multiple times.
console.log("Formatted name", vcard.fn);
console.log("Names", JSON.stringify(vcard.n));
});
//Fore more help:https://github.com/nilclass/vcardjs
}
I want to download pdf file in my android phone using phone gap.can any one help me to download it? i have used https://github.com/phonegap/phonegap-plugins/tree/master/Android/Downloader plugin but it is not working.If anybody have any other downloading method then please let me know..
Thanks in advance..
You can use the phonegap file api to download the files you want from server. Check docs for more detail - FileTransfer API
Here is an example code to download and save a pdf file in your sdcard.
window.appRootDirName = "download_test";
document.addEventListener("deviceready", onDeviceReady, false);
function onDeviceReady() {
console.log("device is ready");
window.requestFileSystem(LocalFileSystem.PERSISTENT, 0, gotFS, fail);
}
function fail() {
console.log("failed to get filesystem");
}
function gotFS(fileSystem) {
console.log("filesystem got");
window.fileSystem = fileSystem;
fileSystem.root.getDirectory(window.appRootDirName, {
create : true,
exclusive : false
}, dirReady, fail);
}
function dirReady(entry) {
window.appRootDir = entry;
console.log("application dir is ready");
}
downloadFile = function(){
var fileTransfer = new FileTransfer();
var url = "http://www.irs.gov/pub/irs-pdf/fw4.pdf";
var filePath = window.appRootDir.fullPath + "/test.pdf";
fileTransfer.download(
url,
filePath,
function(entry) {
alert("download complete: " + entry.fullPath);
},
function(error) {
alert("download error" + error.source);
}
);
}
For full source - https://gist.github.com/3055240
** You must add plugin file API, file transfer in phonegap (3.0+)
function downloadPDF(url, fileName, folder) {
var fileTransfer = new FileTransfer();
var uri = encodeURI(url);
var fileURL = folder + fileName;
fileTransfer.download(
uri,
fileURL,
function(entry) {
alert("complete");
console.log("download complete: " + entry.toURL());
},
function(error) {
alert("upload error code" + error.code);
console.log("download error source " + error.source);
console.log("download error target " + error.target);
console.log("upload error code" + error.code);
},
false,
{
headers: {
"Authorization": "Basic dGVzdHVzZXJuYW1lOnRlc3RwYXNzd29yZA=="
}
}
);
}
in Link
<a href="#"
onclick="
downloadPDF(
'http://cran.r-project.org/doc/manuals/R-intro.pdf',
'R-intro.pdf',
'/sdcard/nuuoeiz/'
);">
Download PDF</a>
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
I wrote an jQuery Mobile app and packaged it with Phonegap to iOS and Android apps.
At this point I am using locally stored json files to read data.
I would like to update these json files from time to time by downloading newer json files from a server.
How can I get the json from the server and store the json files to the local file system of Android and iOS?
Cheers
Johe
Use FileTransfer.download, here is an example:
function downloadFile(){
window.requestFileSystem(LocalFileSystem.PERSISTENT, 0,
function onFileSystemSuccess(fileSystem) {
fileSystem.root.getFile(
"dummy.html", {create: true, exclusive: false},
function gotFileEntry(fileEntry) {
var sPath = fileEntry.fullPath.replace("dummy.html","");
var fileTransfer = new FileTransfer();
fileEntry.remove();
fileTransfer.download(
"http://www.w3.org/2011/web-apps-ws/papers/Nitobi.pdf",
sPath + "theFile.pdf",
function(theFile) {
console.log("download complete: " + theFile.toURI());
showLink(theFile.toURI());
},
function(error) {
console.log("download error source " + error.source);
console.log("download error target " + error.target);
console.log("upload error code: " + error.code);
}
);
}, fail);
}, fail);
};
}
This is how I solved it. First set the file paths, wich are different for Android and iOS
var file_path;
function setFilePath() {
if(detectAndroid()) {
file_path = "file:///android_asset/www/res/db/";
//4 Android
} else {
file_path = "res//db//";
//4 apache//iOS/desktop
}
}
Then I load my JSON files, wich are prepackaged with the app, into the local browser storage. Like this:
localStorage["my_json_data"] = loadJSON(file_path + "my_json_data.json");
function loadJSON(url) {
return jQuery.ajax({
url : url,
async : false,
dataType : 'json'
}).responseText;
}
If I wanna update my data. I get the new JSON Data from the server and push it into the local storage. If the server is on a different domain, which is the case most of the time, you have to make a JSONP call (check jQuery's docs on JSONP).
I did it kinda like this:
$.getJSON(my_host + 'json.php?function=' + my_json_function + '&callback=?', function (json_data) {
//write to local storage
localStorage["my_json_data"] = JSON.stringify(json_data);
});
You can do this in one line of code:
new FileManager().download_file('http://url','target_path',Log('downloaded success'));
target_path: can include directory (example: dira/dirb/file.html) and the directories will be created recursively.
You can find the library to do this here:
https://github.com/torrmal/cordova-simplefilemanagement
My suggestion would be to look into PhoneGap's File API. I haven't used it myself, but it should do what you're after.
Updated Answer for new Cordova
function downloadFile(url, filename, callback, callback_error) {
var fileTransfer = new FileTransfer();
fileTransfer.download(url,
cordova.file.dataDirectory + "cache/" + filename,
function (theFile) {
console.log("download complete: " + theFile.toURL());
if (callback)
callback();
},
function (error) {
console.log("download error source " + error.source);
console.log("download error target " + error.target);
console.log("upload error code: " + error.code);
if (callback_error)
callback_error();
}
);
}
For downloading and displaying a file, follow the sample code.
Include the given code just above the </head> tag in your index.html
< script type = "text/javascript" charset = "utf-8" >
// Wait for Cordova to load
document.addEventListener("deviceready", onDeviceReady, false);
// Cordova is ready
function onDeviceReady() {
alert("Going to start download");
downloadFile();
}
function downloadFile() {
window.requestFileSystem(
LocalFileSystem.PERSISTENT, 0,
function onFileSystemSuccess(fileSystem) {
fileSystem.root.getFile(
"dummy.html", {
create: true,
exclusive: false
},
function gotFileEntry(fileEntry) {
var sPath = fileEntry.fullPath.replace("dummy.html", "");
var fileTransfer = new FileTransfer();
fileEntry.remove();
fileTransfer.download(
"http://www.w3.org/2011/web-apps-ws/papers/Nitobi.pdf",
sPath + "theFile.pdf",
function(theFile) {
console.log("download complete: " + theFile.toURI());
showLink(theFile.toURI());
},
function(error) {
console.log("download error source " + error.source);
console.log("download error target " + error.target);
console.log("upload error code: " + error.code);
}
);
},
fail);
},
fail);
}
function showLink(url) {
alert(url);
var divEl = document.getElementById("deviceready");
var aElem = document.createElement("a");
aElem.setAttribute("target", "_blank");
aElem.setAttribute("href", url);
aElem.appendChild(document.createTextNode("Ready! Click To Open."))
divEl.appendChild(aElem);
}
function fail(evt) {
console.log(evt.target.error.code);
}
</script>
Refer :- Blog Post