Save image to a specific folder using cordova - javascript

I am trying to save an image captured using cordova camera plugin to a specific directory for windows 8.1 application. But I am not able to find an exact solution for this. I have gone through many questions and forums, no luck.
Here is a sample code I have tried.
onTakePhoto: function () {
navigator.camera.getPicture(this.onPhotoSuccess, this.onPhotoFail, {
quality: 100,
destinationType: Camera.DestinationType.FILE_URI,
encodingType: Camera.EncodingType.JPEG,
sourceType: Camera.PictureSourceType.CAMERA,
saveToPhotoAlbum: false
});
},
//Callback function if onTakePhoto action is success.
onPhotoSuccess: function (oImageURI) {
console.log("In Success " + oImageURI);
window.resolveLocalFileSystemURI(oImageURI, this.handlePicSave, this.onPhotoFail);
},
//Callback function if onTakePhoto action fails
onPhotoFail: function (oError) {
console.log("In Fail " + oError);
},
//Handle pic save
handlePicSave: function(oEntry) {
window.requestFileSystem(LocalFileSystem.PERSISTENT, 0, function (fileSys) {
fileSys.root.getDirectory("MyPhotos", { create: true, exclusive: false }, function (directory) {
oEntry.moveTo(directory, "WO_2.jpg", that.successMove, that.onPhotoFail);
}, that.onPhotoFail);
},
that.onPhotoFail);
},
The above code works fine and saves the image to the app root folder i.e C:\Users\..\AppData\Local\Packages\App_name\LocalState\MyPhotos\WO_2.jpg
But I need to store directly to C drive like.. C:\MyPhotos\WO_2.jpg

I think you should check cordova file plugin, It allows to access differents folders and read / write. I do not use it for camera purposes, but I used it for saving files in diferent projects and works fine.

Related

javascript file cordova.. how to pass value through variable

I am developing intel cordova app...
to download files from server , i have included cordova file download plugin but it has data that i want to pass through variable...
here is my code:
var app = {
fileName: "PointerEventsCordovaPlugin.wmv", //<-- pass this value through variable (dynamic)
uriString: "http://media.ch9.ms/ch9/8c03/f4fe2512-59e5-4a07-bded-124b06ac8c03/PointerEventsCordovaPlugin.wmv", // <-- this one also
// Application Constructor
initialize: function() {
this.bindEvents();
},
....
I have added fileName and uristring.. but i want to add that value dynamically from variable.. how can i do this?????
cordova plugin link
please if you know anything about this than reply...
Following the example from the link you provided, remove the fileName and uriString fields from the app object, and parameterize the needed functions. For example, startDownload will become:
startDownload: function (fileName, uriString) {
window.requestFileSystem(LocalFileSystem.PERSISTENT, 0, function(fileSystem) {
fileSystem.root.getFile(fileName, { create: true }, function (newFile) {
app.downloadFile(uriString, newFile);
});
});
},

Jquery : Post Request is breaking while uploading multiple images

I am using Plupload js plugin to upload multiple images in one request. This plugin is working like if someone adding 5 images at a time then post request will go 5 times to upload each of images separately. As we know Post request require unique csrf token but in my case due to same token after one time, post request is failing.
Here is my code ...
<c:set var="csrfTokenVal"><csrf:token-value uri="<%=request.getRequestURI()%>"/></c:set>
<script>
var csrftokenV="${csrfTokenVal}";
$("#uploader").plupload({
// General settings
runtimes : 'html5,flash,silverlight,html4',
url:'/view/SurgeryNotesComponentController?uploadSurgeryImage=true&'+csrftokenN+'='+csrftokenV,
// User can upload no more then 20 files in one go (sets multiple_queues to false)
max_file_count: 10,
chunk_size: '1mb',
// Resize images on clientside if we can
resize : {
width : 600,
height : 610,
quality : 90,
//crop: true // crop to exact dimensions
},
filters : {
// Maximum file size
max_file_size : '1mb',
// Specify what files to browse for
mime_types: [
{title : "Image files", extensions : "jpg,gif,png"},
{title : "Zip files", extensions : "zip"}
]
},
// Rename files by clicking on their titles
rename: true,
// Sort files
sortable: true,
// Enable ability to drag'n'drop files onto the widget (currently only HTML5 supports that)
dragdrop: true,
// Views to activate
views: {
list: true,
thumbs: false, // Show thumbs
active: 'thumbs'
},
init: {
FilesAdded: function(up, files) {
$("#uploader_filelist").show();
},
FileUploaded: function(up, file, info, res) {
var imageObjectArray=$.parseJSON(info.response);
for(i=0;i<imageObjectArray.objectList.length; i++){
$('#showfilelist ul').append("<li><a class='delIcon-image' href='#delete' id='delSurgeryImageIcon'></a><a id=" + imageObjectArray.objectList[i].uid + " class='cboxElement imguid' href='${contextPath}/view/SurgeryNotesComponentController?surgeryImage=true&"+csrftokenN+ "="+ csrftokenV+"&attachmentLocation="+imageObjectArray.objectList[i].attachmentLocation+"' target='_blank'><img src='${contextPath}/view/SurgeryNotesComponentController?surgeryImage=true&"+csrftokenN+ "="+ csrftokenV+"&attachmentLocation="+imageObjectArray.objectList[i].attachmentLocation+"' border='0'>"+"</a> <strong>"+noteAddedMsg+"</strong><span class='image-created'>"+imageObjectArray.objectList[i].formattedDate+" "+byMsg+" "+imageObjectArray.objectList[i].userName+" </span></li>");
}
$("#uploader_filelist").empty().hide();
_SPINE.colorboxOverlay.coloboxPopup();
_SPINE.surgeryNotes.deleteImages();
$(".plupload_done .plupload_file_thumb").removeClass("hide")
},
ChunkUploaded: function (up, file, response) {
response = $.parseJSON(response.response || "null");
if (response.chunk == 3) {
up.stop();
up.start();
}
console.log(file.loaded);
}
},
// Flash settings
flash_swf_url : '${siteAssetsUrl}/assets/spine/js/external/Moxie.swf',
// Silverlight settings../assets/js
silverlight_xap_url : '${siteAssetsUrl}/assets/spine/js/external/Moxie.xap'
});
</script>
Here you can see I am generating scrf token (csrftokenV) and sending it in url to make it post supported.
Now the problem is if I am uploading more than 1 images (lets say 3), then 3 time post request will go. Each time i will get same csrf token and after uploaing first image, furthure images will not work and i will get this exception ....
WARNING: potential cross-site request forgery (CSRF) attack thwarted (user:<anonymous>, ip:127.0.0.1, uri:/**/image, error:request token does not match session token)
Please help me to solve this problem. Thanks
Finally One of my friend had solved the issue. It can't be possible to handle this issue through client side script so we leverage the power of Java. We had updated the csrfToken based on new request and sent it out with response.
Here is a solution ..
private String updateToken(HttpServletRequest request)
{
final HttpSession session = request.getSession(false);
CsrfGuard csrfGuard = CsrfGuard.getInstance();
csrfGuard.updateTokens(request);
String newToken=(String) session.getAttribute(REQUEST_TOKEN);
return newToken;
}
Setting newToken in response ...
response.setResult(this.updateToken(request));
return response;
Now we can change the url in beforeUpload event and set new token in the url.
BeforeUpload: function(up, file)
{
up.settings.url='/view/SurgeryNotesComponentController?uploadSurgeryImage=true&'+csrftokenN+'='+tokenRefresh
}
FileUploaded: function(up, file, info, res)
{
var imageObjectArray=$.parseJSON(info.response);
tokenRefresh=imageObjectArray.result;
}

Cordova WP8 resolveLocalFileSystemURL fails

Good day, i have a project on cordova that uses image gallery and camera and stores images in local cache folder.
So i installed:
org.apache.cordova.camera 0.3.1 "Camera"
org.apache.cordova.file 1.3.1 "File"
org.apache.cordova.file-transfer 0.4.6 "File Transfer"
Android and iOS works perfectly, but when it comes to WP8 (Windows Phone 8), following code:
$scope.uploadImageFromPhone = function(isCamera){
console.log('uploadImageFromPhone');
var opt = {
quality: 50,
destinationType: Camera.DestinationType.FILE_URI,
sourceType: (isCamera) ? Camera.PictureSourceType.CAMERA : Camera.PictureSourceType.PHOTOLIBRARY,
encodingType: Camera.EncodingType.JPEG
};
function onGetImageSuccess(fileUrl) {
console.log('onGetImageSuccess:\n'+fileUrl);
window.resolveLocalFileSystemURL(fileUrl, resolveSuccess, resolveFails);
}
function onGetImageFail(message) {
//console.log('onGetImageFailed:\n' + JSON.stringify(message));
}
function resolveSuccess (path) {
console.log('resolveSuccess:');
console.log(JSON.stringify(path));
uri = path.nativeURL;
//wp8 returns null as path.nativeURL
/*IE10 specific hack*/
if (navigator.userAgent.match(/IEMobile\/10\.0/)) {
uri = path.fullPath;
}
}
function resolveFails(err){
console.log('resolveFails:\n' + JSON.stringify(err));
};
navigator.camera.getPicture(onGetImageSuccess, onGetImageFail, opt);
}
The resolveSuccess function always returns path variable as shown below:
{"isFile":true,"isDirectory":false,"name":"wp_ss_20140923_0001.png","fullPath":"///CapturedImagesCache/wp_ss_20140923_0001.png","filesystem":"<FileSystem: temporary>","nativeURL":null}
Problem is that nativeURL is null.
According to my app, chosen file must be put in application local cache, so i try to download it and store in cache by approaching to fullPath with file-transfer plugin:
var fileTransfer = new FileTransfer();
fileTransfer.download(
uri, // equals to '///CapturedImagesCache/wp_ss_20140923_0001.png'
'wp_ss_20140923_0001.png',
function(entry){
//file processing
console.log('downloaded successfull');
},
function(error){
console.log("download error" + JSON.stringify(error));
},
false,
{}
);
This code always returns me console output:
download error: {"code":2,"source":"///CapturedImagesCache/wp_ss_20140923_0001.png","target":null,"http_status":null,"body":null,"exception":null}
I don't get it, what am i doing wrong here?
P.S: cordova version: '3.6.3-0.2.13'

Onsenui: sliding menu + camera

I'm using monaca ide to develop a simple app, and using the slinding menu of onsenui I found that usually when I take a photo reload the page, so the photo doesn't appear on the page. Seems to be random, sometimes happen sometimes doesn't, and I could find why. Any idea?
UPDATE:
Here you could see the controller where action is handle:
var appControllers = angular.module('appControllers', []);
appControllers
.controller('parkingCtrl', [
'$scope',
'appGlobals',
function($scope, appGlobals) {
$scope.snapPhoto = function() {
navigator.camera.getPicture (onSuccess, onFail, {
quality: 50,
destinationType: Camera.DestinationType.FILE_URI,
targetWidth: 100
});
//A callback function when snapping picture is success.
function onSuccess (imageURI) {
$scope.$apply(function(){
$scope.imageURI = imageURI;
});
}
//A callback function when snapping picture is fail.
function onFail (message) {
alert ('Error occured: ' + message);
}
}
])
I guess this happens on Android.
When you call the function to take picture, the Camera app take over, and now your app is in the background. If you take big picture and your device has small memory, your device will be in low memory state, and it has to kill some background apps to free the memory. In some case, your app is killed and when you return back from the Camera app, your app is restarted.
A work around is to limit the quality or the size of the picture.
This is the reference to the api:
http://docs.phonegap.com/en/2.9.0/cordova_camera_camera.md.html#Camera
navigator.camera.getPicture(onPhotoDataSuccess,
onFail,
{ quality: 75,
allowEdit: true,
destinationType: destinationType.DATA_URL,
targetWidth: 100,
}
);
Here is the complete options:
{ quality : 75,
destinationType : Camera.DestinationType.DATA_URL,
sourceType : Camera.PictureSourceType.CAMERA,
allowEdit : true,
encodingType: Camera.EncodingType.JPEG,
targetWidth: 100,
targetHeight: 100,
popoverOptions: CameraPopoverOptions,
saveToPhotoAlbum: false };
but your case is different..
1) your pic could be so big. so insted of just reloading the page you should hard reload that page
right click on back button

How would I get a File object from PhoneGap camera.getPicture?

This is probably simple and covered by some combination of functions in PhoneGap's "Camera" plugin, "File" plugin, or "File-Transfer" plugin. I understand the user can select a file with:
navigator.camera.getPicture(function (fileURI) {
// *** need help here ***
}, function ()
// handle errors
}, {
destinationType: window.Camera.DestinationType.FILE_URI,
sourceType: window.Camera.PictureSourceType.PHOTOLIBRARY,
mediaType: window.Camera.MediaType.ALLMEDIA
});
I can also change to destinationType: window.Camera.DestinationType.DATA_URL if that makes a difference.
My goal in the success handler is to get a File object (https://developer.mozilla.org/en-US/docs/Web/API/File).
Something like this should do it.
navigator.camera.getPicture(function (fileURI) {
window.resolveLocalFileSystemURL(fileURI,
function(fileEntry){
alert("got image file entry: " + fileEntry.fullPath);
// fileEntry.file() should return a raw HTML File Object
},
function(){//error}
);
}, function (){
// handle errors
}, {
destinationType: window.Camera.DestinationType.FILE_URI,
sourceType: window.Camera.PictureSourceType.PHOTOLIBRARY,
mediaType: window.Camera.MediaType.ALLMEDIA
});
window.resolveLocalFileSystemURI(fileURI, function(fileEntry) { /* your code here */ });

Categories