cordova File Transfer plugin not uploading video to Server - android

I'm creating an Hybrid app in which I want to upload video to
server. Sometimes it uploads the video to the server but most of the
time Plugin shows the uploading progress to 99% and then it gives
null in success callback.
Thanks in advance. :-)
/********* OPENING CAMERA TO CPTURE VIDEO ***********/
function make_Video()
{
// capture callback
var captureSuccess = function(mediaFiles) {
var i, len , video_path;
if(mediaFiles.length > 0)
{
for (i = 0, len = mediaFiles.length; i < len; i += 1)
{
video_path = mediaFiles[i].fullPath;
Upload_Video(video_path);
}
}
};
// capture error callback
var captureError = function(error)
{
console.log('Error Code: ' + error.code);
};
navigator.device.capture.captureVideo(captureSuccess, captureError, { quality: 100,destinationType: Camera.DestinationType.FILE_URI });
}
/****************STORING VIDEO ON SERVER******************/
function Upload_Video(video_path)
{
var server = server_link; // MY SERVER LINK
var params = {'user_id':logged_in_user_id,'action':'update_intro_video'};
if (server)
{
// Specify transfer options
$('#modal_first_line').text(0+" %"+" Uploaded");
$('#new_modal').show();
var options = new FileUploadOptions();
options.fileKey = "user_video";
options.fileName = video_path.substr(video_path.lastIndexOf('/')+1);
options.mimeType = "video/mp4";
options.chunkedMode = false;
options.httpMethod = "POST";
options.params = params;
// Transfer picture to server
var ft = new FileTransfer();
//progree bar
ft.onprogress = function(progressEvent) {
if (progressEvent.lengthComputable){ var perc = Math.floor(progressEvent.loaded / progressEvent.total * 100); $('#modal_first_line').text(perc+" %"+"
Uploaded"); } else {$('#new_modal').hide();
console.log("sorry! Upload Failed..."); } };
ft.upload(video_path, encodeURI(server) , function(data) {
$('#new_modal').hide();
console.log("SERVER RESPONSE: " + JSON.stringify(data));
},
function(error)
{
$('#new_modal').hide();
console.log("sorry! Upload Failed...");
}, options);
}
else{
$('#new_modal').hide();
console.log("sorry! Can't Upload File.");;
}
}

Solved.
The Problem was at server end. Configuration was making
trouble. post_max_size was set to 8Mb, so when limit of video
exceeds to 8MB, server was not allowing to save the video. I
increased the post_max_size to 100MB. To Increase the post_max_size
, I did the following steps
1. I Created a file .user.ini in the root directory
2. I placed the following code inside this file
file_uploads = O post_max_size = 100M upload_max_filesize
= 200M
Hope it will help someone.

Related

Error playing back video uploaded via PhoneGap FileTransfer

I've been stuck on this issue for awhile and i can't seem to find a solution. What i am trying to achieve is this:
Select a video from the phone's library
Upload the video to Amazon AWS using a signed PUT url
Download the uploaded video and play it back on the PC
I am able to select the video from the phone's gallery and successfully upload it to Amazon aws. However, when i try to open and playback the file, media player says that the file format is not supported.
It cannot be a codec issue with my player because i can playback other videos that were uploaded to amazon (via standard HTML file input). Plus, when i transfer the same video from my phone to the desktop, it is playable.
I have a feeling that i'm missing out something when setting up the FileTransfer object. Below is a snippet of my code:
navigator.camera.getPicture(
function(imgUrl) {
that.mDialogOpen("Uploading video...");
window.resolveLocalFileSystemURL(imgUrl, function(fileEntry) {
fileEntry.file(function(file) {
var parts = fileEntry.nativeURL.split('/');
var filename = parts[parts.length - 1];
// Params is sent to the server to generate the signed amazon put url
var params = {'a':'handlerFunctionKey', 'name':filename, 'type':'multipart/encrypted'};
var callback = function(data) {
alert("In callback");
var dataResp = data['handlerFunctionKey'];
if (dataResp.status == 'SUCCESS') {
var amazonUrl = decodeURIComponent(dataResp.object);
alert("Setting up options: " + file.type);
var ftOptions = new FileUploadOptions();
ftOptions.fileName = filename;
ftOptions.mimeType = file.type;
ftOptions.chunkedMode = false;
ftOptions.headers = {'Content-Type':"multipart/encrypted",'x-amz-acl':'public-read',"Connection":"close"};
ftOptions.httpMethod = 'PUT';
var ft = new FileTransfer();
ft.upload(imgUrl, amazonUrl,
function() {
$("#mModalText").html("Upload success");
},
function(err) {
alert("Upload error: " + err.code);
alert("Upload target: " + err.target);
alert("Upload source: " + err.source);
}, ftOptions, true);
}
};
that.doAjax(params, callback); // Execute ajax call to server and run the callback function upon response
}, function() {});
}, function() {});
},
function() {}, options);
The 'options' for the getPicture function are:
var options = {quality:50, destinationType:Camera.DestinationType.FILE_URI};
options['sourceType'] = Camera.PictureSourceType.PHOTOLIBRARY;
options['mediaType'] = Camera.MediaType.VIDEO;
options['targetWidth'] = 640;
options['targetHeight'] = 480;
The video i'm uploading is a MP4 with mimeType 'video/mp4'. I'm testing this on an Android. I'm building the code with Phonegap version 6.0.1 via remote build.
Thanks in advance.

how to select any file and upload in cordova hybrid mobile app

I am creating a mobile app using cordova phonegap and visualstudio.
My question is: Is there any way a user of the app can select any file(not only images) from the mobile device and upload.
I am trying to use the file-transfer plugin and the input file tag for the user to select the file. When i click on the the file i can select only image files.
Also i get an error related to the fileURI
URI not supported by CordovaResourceApi
Till now my code is:
function uploadmsg() {
try {
var fileURI;
fileURI = $('#fli').val();
console.log(fileURI);
var win = function (r) {
console.log('Uploaded');
}
var fail = function (error) {
console.log(error);
}
var options = new FileUploadOptions();
options.fileKey = "file";
options.fileName = fileURI.substr(fileURI.lastIndexOf('/') + 1);
options.mimeType = document.getElementById('fli').files[0].type;
var postData = $('#frmim').serialize();
options.params = '{' + postData + '}'; // if we need to send parameters to the server request
var ft = new FileTransfer();
ft.upload(fileURI, encodeURI("http://someurl"), win, fail, options);
}
catch (err) {
console.log(err.message);
}
}

Titanium Synchronization

i have problem to sync local image folder to server, i using titanium. When i run my program using android emulator, it works well. But when i try to run it using actual device, the program can not find the image file.
Below is my code. Please help.
$.btnfiles.addEventListener('click',function(e)
{
var dirTest = Titanium.Filesystem.getFile(Titanium.Filesystem.applicationDataDirectory);
var dirList = dirTest.getDirectoryListing();
Titanium.API.info('Start loop for files length:' + dirList.length);
for ( i = 0; i < dirList.length; ++i){
var f = Titanium.Filesystem.getFile(Titanium.Filesystem.applicationDataDirectory, dirList[i]);
var data_to_send = {
"file": f.read(), "name1":Titanium.Filesystem.applicationDataDirectory
};
xhr = Titanium.Network.createHTTPClient({
// function called when an error occurs, including a timeout
onerror : function(e) {
//Ti.API.debug(e.error);
alert('error');
},
timeout : 5000 // in milliseconds
});
xhr.setRequestHeader("enctype", "multipart/form-data");
xhr.open("POST","upload.php");
xhr.send(data_to_send);
Titanium.API.info('Namef: ' + dirList[i]);
Titanium.API.info('Name: ' + i);
var file = Titanium.Filesystem.getFile(Titanium.Filesystem.applicationDataDirectory,dirList[i]);
if (file.exists()) { file.deleteFile(); }
}
});

Trying to upload image from app in phonegap... Getting error code 1?

I'm able to upload an image using the the camera, but I can't seem to get the correct file name to upload (error code 1 NOT_FOUND_ERR) when trying to upload a file from my app. What I'm trying to do is upload a default profile image to server when a user first signs up.
Here is my code, which is almost identical to the working camera upload I have:
// Source
path = 'images/default.jpeg';
// Destination
var url = 'http://serverloc/data';
// Upload Options
var options = new FileUploadOptions();
options.fileKey = 'file';
options.fileName = path.substr(path.lastIndexOf('/') + 1);
options.mimeType = 'image/jpeg';
options.chunkedMode = false;
var params = new Object();
params.fullpath = path;
params.name = options.fileName;
options.params = params;
// Upload
var ft = new FileTransfer();
ft.upload(path, url,
function(result) {
// hasn't worked yet
},
function(error) {
alert('Error uploading default image: ' + error.code);
// 1 - NOT_FOUND_ERR
},
options);
Testing on Android.
Update: Since I can't this working, I guess my next best option is to add a marker property for each user, and if that propery (default-img say) is "yes", then I'll display the default image in-app, rather than having it stored on the server.

How to move captured image in PhoneGap to a folder in sdcard

I am using following code to get image base64 data to display and upload to server.
But i want to save this captured image in sdcard folder. Please help me to do this.
This is necessary for me to get base64 image data because server support only this format. That's why i am using destinationType = 0 (means DATA_URL). I have base64 image data now but how can i save this data to sdcard?
uploadPhoto(isSourceCamera, onPhotoDataSuccess, onFail);
function uploadPhoto(isSourceCamera, onPhotoDataSuccess, onFail)
{
pictureSource = navigator.camera.PictureSourceType;
if (isSourceCamera)
{
//QUALITY MUST BE LOW TO AVOID MEMORY ISSUES ON IPHONE4 ! (and other low memory phones).
//must resize to make it faster to upload and avoid failure with low memory phones.
navigator.camera.getPicture(onSuccessFunc, onFail, {
quality : 35,
sourceType : pictureSource.CAMERA,
targetWidth:750,
targetHeight:750,
allowEdit:true,
destinationType:0
});
}
else
{
navigator.camera.getPicture(onSuccessFunc, onFail, {
quality : 35,
sourceType : pictureSource.PHOTOLIBRARY,
targetWidth:750,
targetHeight:750,
allowEdit:true,
destinationType:0
});
}
}
function onPhotoDataSuccess(imageData)
{
**//I want to smae my image here in sdcard folder.**
var nodeid = localStorage.getItem("user_nodeid");
var modifyImgData = imageData.replace(' ', '+');
document.getElementById('image').src = setLocalStorageImage(localStorage.getItem(nodeid+"image"), modifyImgData);
document.getElementById('profileMenu').src = setLocalStorageImage(localStorage.getItem(nodeid+"smallimage"), modifyImgData);
$.ajax({
type: "POST",
url: appURL+"api/upload/image/" +nodeid+ "/1",
data: "image=" + encodeURIComponent(modifyImgData),
success: function(msg){
//No need to do anything here
if (msg.documentElement.getElementsByTagName("message")[0].childNodes[0].nodeValue != 'success')
onFail('Error in uploading image at server. Please try again.');
}
});
}
function onFail(message){
alert(message);
}
Here is the correct answer to the original question:
How to move captured image in PhoneGap to a folder in sdcard?
function onfail(error,caller){
error = error || '[error]';
caller = caller || '[caller]';
alert('Error > '+caller+" code: "+error.code);
};
/*
Error codes
NOT_FOUND_ERR = 1;
SECURITY_ERR = 2;
ABORT_ERR = 3;
NOT_READABLE_ERR = 4;
ENCODING_ERR = 5;
NO_MODIFICATION_ALLOWED_ERR = 6;
INVALID_STATE_ERR = 7;
SYNTAX_ERR = 8;
INVALID_MODIFICATION_ERR = 9;
QUOTA_EXCEEDED_ERR = 10;
TYPE_MISMATCH_ERR = 11;
PATH_EXISTS_ERR = 12;
*/
function doCameraAPI() {
// Retrieve image file location from specified source
navigator.camera.getPicture(getImageURI, function(message) {
alert('Image Capture Failed');
}, {
quality : 40,
destinationType : Camera.DestinationType.FILE_URI
});
}; //doCameraAPI
function getImageURI(imageURI) {
//resolve file system for image to move.
window.resolveLocalFileSystemURI(imageURI, gotFileEntry, function(error){onfail(error,'Get Target Image')});
function gotFileEntry(targetImg) {
//alert("got image file entry: " + targetImg.name);
//now lets resolve the location of the destination folder
window.resolveLocalFileSystemURI(POSTPATH, gotDestinationEntry, function(error){onfail(error,'Get Destination Dir')});
function gotDestinationEntry(destination){
// move the file
targetImg.moveTo(destination, targetImg.name, moveSuccess, function(error){onfail(error,'Move Image')});
alert('dest :'+destination.fullPath);
};
function moveSuccess(){
alert('FILE MOVE SUCCESSFUL!');
};
}; //getImageURI
credit to: nbk on the google phonegap group.
Since you have the data in Base64 format you can just use the FileWriter to save the data to disk.
I think you need to capture the image as FILE_URL, and save the image to sdcard first as mentioned by Steven Benjamin above.
Then you can retrive the base64 DATA_URL as
function readFile() { // button onclick function
var gotFileEntry = function(fileEntry) {
console.log("got image file entry: " + fileEntry.fullPath);
fileEntry.file( function(file) {
var reader = new FileReader();
reader.onloadend = function(evt) {
console.log("Read complete!");
image64.value = evt.target.result;
};
reader.readAsDataURL(file);
}, failFile);
};
window.resolveLocalFileSystemURI("file:///mnt/sdcard/test.jpg", gotFileEntryImage, function(){console.log("* * * onPhotoURISuccess" + failed);});
}

Categories

Resources