Cordova file upload not working on android - android

using cordova media-capture and file-transfer plugin I try to make an app to record video and upload on server. After recording video I call the upload function and it showing the success message in success callback function. But no file uploaded in server. Here my code.
$(document).ready(function(){
document.addEventListener("deviceready", onDeviceReady, false);
});
function onDeviceReady() {
navigator.device.capture.captureVideo(captureSuccess, captureError, {limit:1});
}
var captureSuccess = function(mediaFiles) {
var i, len;
for (i = 0, len = mediaFiles.length; i < len; i += 1) {
uploadFile(mediaFiles[i]);
}
};
var captureError = function(error) {
alert('error');
console.log(error);
};
/********* File Upload **********/
// Upload files to server
function uploadFile(mediaFile) {
var ft = new FileTransfer(),
path = mediaFile.fullPath,
name = mediaFile.name;
ft.upload(path,
"http://myserver.com/test.php",
function(result) {
alert('success');
},
function(error) {
alert('error');
},
{ fileName: name, fileKey: "file" });
}
My php code is
<?php
if($_FILES['file']['size'] > 0) {
$path = $_SERVER['DOCUMENT_ROOT']."/audior/app/";
$tmpname1 = $_FILES['file']['tmp_name'];
$ptname1 = $_FILES['file']['name'];
move_uploaded_file($tmpname1, $path . $ptname1);
echo 'success';
}
?>

You have to create a FileUploadOptions object
var options = new FileUploadOptions();
options.fileKey = "file";
options.fileName = name;
then use it on the upload function
ft.upload(path,
"http://myserver.com/test.php",
function(result) {
alert('success');
},
function(error) {
alert('error');
},
options);
You can also change the
function(result) {
alert('success');
}
to
function(result) {
alert(result);
}
Just to check if the server is telling you something.
If you are getting the success callback the problem should be on the PHP script.
I use this one that returns the url of the uploaded file
<?php
$target_dir = "upload/";
$target_file = $target_dir . basename($_FILES["file"]["name"]);
move_uploaded_file($_FILES["file"]["tmp_name"], "./" . $_FILES["file"]["name"]);
echo "http://" . $_SERVER['SERVER_NAME'] . "/" . $target_file;
?>

Related

Display image from internal storage in Vue + Cordova

I am trying to display an image from download folder.
imagePath: file:///storage/emulated/0/Download/sample.png
Set Image URL:
window.resolveLocalFileSystemURL(this.imagePath, function success(fileEntry) {
fileEntry.file(function (file) {
var reader = new FileReader();
reader.onloadend = function() {
if (this.result) {
var blob = new Blob([new Uint8Array(this.result)], { type: "image/png" });
this.imgUrl = window.URL.createObjectURL(blob);
}
};
reader.readAsArrayBuffer(file);
});
}, function (err) {
this.info = 'An error was found: '+ err;
});
Display it on UI:
<img class="img-fluid" src="{{imgUrl}}" />
But code is not reaching inside onloadend callback.

Display PDF in Android/iOS App

I have downloaded a PDF file as Base64 String in my phone as described in this SO Thread but I am not getting how can I render it to actual PDF so that end user can see it? I have written following code to write on the file:
var tempResponse = null;
function downloadFileOK(response){
var invocationResult = response['invocationResult'];
tempResponse = invocationResult;
var size = parseInt(invocationResult["responseHeaders"]["Content-Length"]);
window.requestFileSystem(LocalFileSystem.PERSISTENT, size, onSuccessFileHandler, onErrorFileHandler);
}
//Success
function onSuccessFileHandler(fileSystem) {
alert("inside onSuccessFileHandler START");
fileSystem.root.getFile("test2.pdf", {create: true, exclusive: false}, fileWriter, fail);
alert("inside onSuccessHandler END");
}
// Failure
function onErrorFileHandler(error) {
alert("inside onErrorFileHandler");
}
function fileWriter(entry){
alert("inside fileWriter START");
entry.createWriter(function(writer){
writer.onwriteend = function(evt) {
console.log("done written pdf :: test1.pdf");
alert("Inside onwriteend : START");
};
var temp = atob(tempResponse["text"]);
alert(temp);
writer.write(temp);
},fail);
alert("inside fileWriter END");
}
function fail(error) {
alert("inside fail");
console.log(error.code);
}
Am I doing it wrong? How can I open the PDF from my app in iOS/Android OS using javascript/jquery/cordova ?
Once you have download the base64 encoded file, you should decode it and save it to the file system so that it can be viewed later. You should not save the base in it's base64 encoded form.
You can use the utility function below to accomplish that. BTW you should take a look a the previous answer on Download PDF file from through MobileFirst Adapter since I made an update to it, it wasn't encoding the PDF properly.
var AppUtils = (function(){
// get the application directory. in this case only checking for Android and iOS
function localFilePath(filename) {
if(device.platform.toLowerCase() === 'android') {
return cordova.file.externalDataDirectory + filename;
} else if(device.platform.toLowerCase() == 'ios') {
return cordova.file.dataDirectory + filename;
}
}
// FileWritter class
function FileWritter(filename) {
this.fileName = filename;
this.filePath = localFilePath(filename);
}
// decode base64 encoded data and save it to file
FileWritter.prototype.saveBase64ToBinary = function(data, ok, fail) {
var byteData = atob(data);
var byteArray = new Array(byteData.length);
for (var i = 0; i < byteData.length; i++) {
byteArray[i] = byteData.charCodeAt(i);
}
var binaryData = (new Uint8Array(byteArray)).buffer;
this.saveFile(binaryData, ok, fail);
}
// save file to storage using cordova
FileWritter.prototype.saveFile = function(data, ok, fail) {
this.fileData = data;
var path = this.filePath.substring(0, this.filePath.lastIndexOf('/'));
var that = this;
// Write file on local system
window.resolveLocalFileSystemURL(path, function(directoryEntry) {
var options = {create: true, exclusive: false};
directoryEntry.getFile(that.fileName, options, function(file) {
file.createWriter(function(writer) {
writer.onwriteend = function(event) {
if(typeof ok === 'function') {
ok(event);
}
};
writer.write(that.fileData);
}, fail);
}, fail);
}, fail);
};
// open InApp Browser to view file
function viewFile(filename) {
var path = localFilePath(filename);
window.open(path, "_blank", "location=yes,hidden=no,closebuttoncaption=Close");
}
return {
FileWritter: FileWritter,
localFilePath: localFilePath,
viewFile: viewFile
}
})();
Your downloadFileOK should look as follow:
function downloadFileOK(response){
var pdfData = response['invocationResult']['text'];
var fileWritter = new AppUtils.FileWritter('YOUR-PDF-NAME.pdf');
fileWritter.saveBase64ToBinary(pdfData, function(r){
// file was saved
}, function(e){
// error file was not saved
});
}
If you want to open the file then you can use AppUtils.viewFile('YOUR-FILE-NAME.pdf')

Send a picture using cordova on android

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

Phonegap (3.3.0) FileReader readAsText() not working

so I am trying to use the phonegap file API to save and later load a file in the app. The save seems to be working, but reading the file throws this error:
processMessage failed: Stack: TypeError: Object #<an Object> has no method 'readAsText'
at [object Object].readAsText (file:///android_asset/www/plugins/org.apache.cordova.file/www/FileReader.js:130:33)
at file:///android_asset/www/index.html:3843:15
at file:///android_asset/www/plugins/org.apache.cordova.file/www/DirectoryEntry.js:100:9
at Object.callbackFromNative (file:///android_asset/www/phonegap.js:292:54)
at processMessage (file:///android_asset/www/phonegap.js:1029:21)
at Function.processMessages (file:///android_asset/www/phonegap.js:1063:13)
at pollOnce (file:///android_asset/www/phonegap.js:933:17)
at pollOnceFromOnlineEvent (file:///android_asset/www/phonegap.js:928:5)
No matter what I do, it always seems to throw this error. I printed out the fileReader object to the console and inspected it using weinre. It had the prototype with the readAsText() function on it, so I'm really at a loss why it's not working...
This is how I am saving the file:
var request = window.requestFileSystem;
if(typeof request != 'undefined') {
var fileSystem;
var writer;
request(LocalFileSystem.PERSISTENT, 0, function (FS) {
fileSystem = FS;
fileSystem.root.getFile("offlineData.txt", {create: true, exclusive: false}, function(fileEntry) {
fileEntry.createWriter(function(w) {
writer = w;
writer.write('This is some text yo');
}, function(e) {console.log(e);});},
function(e) {console.log(e); console.log('There was an error getting the file to write')});} ,
function(e) {\console.log('There was an error getting the file system');});}
Later in the flow, I will do something like this:
request(LocalFileSystem.PERSISTENT, 0, function(FS) {
fileSystem = FS;
fileSystem.root.getFile("offlineData.txt", null, function(_file) {
var reader = new FileReader();
reader.onloadend = function (evt) {
console.log("read success");
console.log(evt.target.result);
};
reader.onerror = function(evt) {
console.log("Error read text");
console.log("Error"+evt.error.code);
};
reader.onabort = function(evt) {
console.log("aborted read text");
console.log(evt.target.result);
};
reader.onloadstart = function(evt) {
console.log("started reading");
};
console.log(reader);
reader.readAsText(_file);
});
}, function(e) {console.log(e); console.log('There was an error getting the file.')});
In your sample, _file is a fileEntry and not file content. Can you try this :
fileSystem.root.getFile("offlineData.txt", null,
function (fileEntry) {
fileEntry.file(function (_file) {
var reader = new FileReader();
reader.onloadend = function () {
console.log("read success");
console.log(evt.target.result);
};
reader.readAsText(_file);
});
}
);

How to store and retrieve files in/from android app space?

I'm developing a cordova/phonegap app. Right now, I'm testing the app on Android.
If I include files (audio, video, ...) by default, I can access to that files indicating the "url" like audio/filesong.mp3 or video/filevideo.mp4.
But if I download files with the next code:
function downloadFile() {
var fileTransfer = new FileTransfer();
var uri = encodeURI("UrlOfTheFile");
var fileURL = "cdvfile://localhost/persistent/appcustomstorage/";
fileTransfer.download(
uri, fileURL + "file.extension", function(entry) {
console.log("download complete: " + entry.toURL());
}, function(error) {
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=="
}
});
}
I download the file in StorageRoot/appcustomstorage/file.extension
It is possible to store the file in the app package, i.e., in, for example, Android/data/com.example.app??
Or a method to get the Android/data/com.example.app url and then add the necessary folder?
Solution:
In this case I find all mp3 in the device. It works on Nexus 4.
index.html
<ul data-role="listview" data-inset="true" id="ulsongs">
</ul>
index JavaScript:
document.addEventListener("deviceready", onDeviceReady, false);
// device APIs are available
function onDeviceReady() {
window.requestFileSystem(LocalFileSystem.PERSISTENT, 0, gotFS, fail);
}
function gotFS(fileSystem) {
FileSystem = fileSystem;
// Call to start to find all files
getFileSystem();
}
storageScript:
var FileSystem = null;
var AudioExtensions = [ '.mp3' ];// , '.wav', '.m4a' ];
var my_media = null;
function listDir(directoryEntry, level) {
if (level === undefined)
level = 0;
var directoryReader = directoryEntry.createReader();
directoryReader.readEntries(function(entries) { // success get files and
// folders
for ( var i = 0; i < entries.length; ++i) {
if (entries[i].name === '.')
continue;
if (entries[i].isDirectory) {
FileSystem.root.getDirectory(entries[i].fullPath.slice(1,
entries[i].fullPath.length), {
create : false
}, function(dirEntry) {
listDir(dirEntry, level + 1);
}, function(error) {
console.log('ERROR');
alert(error.code);
});
}
if (entries[i].isFile) {
var extension;
extension = entries[i].name.substr(entries[i].name
.lastIndexOf('.'));
if (entries[i].isFile === true
&& $.inArray(extension, AudioExtensions) >= 0) {
// Add a song to the list
$("#ulsongs").append(
"<li id='" + entries[i].fullPath + "'"
+ " data-icon=\"audio\"><a>"
+ entries[i].name + "</a></li>");
$('#ulsongs').listview('refresh');
}
}
}
}, function(error) { // error get files and folders
alert('Error. Code: ' + error.code);
});
// Action listener
$('#ulsongs li').click(function(e) {
pathsong = $(this).attr('id');
console.log('item clicked. Path: ' + pathsong);
if (typeof (pathsong) != 'undefined' && pathsong != null) {
// Stop previous song
if ((audio_status != null) && (audio_status == 2)) {
console.log('STOP AUDIO');
my_media.stop();
my_media.release();
}
// Play the audio file at url
my_media = new Media(pathsong,
// success callback
function() {
console.log("playAudio():Audio Success");
},
// error callback
function(err) {
console.log("playAudio():Audio Error: " + err);
}, status);
// Play audio
my_media.play();
}
});
}
var audio_status = null;
function status(stat) {
audio_status = stat;
}
/**
*
*/
function getFileSystem() {
console.log('entra getFileSystem');
window.requestFileSystem(LocalFileSystem.PERSISTENT, 0,
function(fileSystem) { // success get file system
var sdcard = fileSystem.root;
sdcard.getDirectory('', {
create : false
}, function(dirEntry) {
listDir(dirEntry);
}, function(error) {
alert(error.code);
})
}, function(evt) { // error get file system
console
.log('ERROR GETTING FILE SYSTEM'
+ evt.target.error.code);
});
}
I create a list of mp3.
I use jQuery and jQueryMobile
Edit
The process may need a bit of time. It is recommended to show a loading popup.

Categories

Resources