This has been asked several times, but most of these questions are unanswered
I'm downloading a file like below, and it seems to work fine. However .. it does not show up in the iOS, ehm, gallery. That is, in the 'photos' application.
var fileTransfer = new FileTransfer();
var encurl = encodeURI(url);
var filename = url.split('/').slice(-1)[0];
var filepath = "foo/"+filename;
window.requestFileSystem(LocalFileSystem.PERSISTENT, 0, function (fileSystem) {
var syspath = fileSystem.root.toURL() + '/' + filepath;
var fileTransfer = new FileTransfer();
fileTransfer.download(
encurl,
syspath,
function (entry) {
foo.debug("Download success "+syspath);
},
function (error) {
foo.error("Download failed with error "+error.code+' '+syspath);
}
);
}, function (evt) {
foo.error("Filesystem failed with error "+evt.target.error.code);
});
and the result is
[Log] Download success file:///var/mobile/Applications/68DE0AD9-FBD2-4D82-92C0-2B7634B218D5/Documents//foo/20141030-153810-editor.jpg (console-via-logger.js, line 173)
hurray. now, how do you open the download, using just your fingers, on ios ?
I would mark this as a duplicate of Phonegap - Save image from url into device photo gallery
I was happy with the answer by M165437 and my comments. That answered my question.
Try to download by using https://www.npmjs.com/package/com-cordova-image-save-to-gallery plugin. It will download a picture from a given URL and save it to IOS Photo Gallery.
Cordova plugin add https://github.com/valwinjose007/cordova-image-save-to-gallery.git
How to use:
declare var CordovaImageSaveToGallery: any;
CordovaImageSaveToGallery.downloadFromUrl('https://picsum.photos/200/300',(res)=>{
//download success
},(err)=>{
//error on download
});
Related
Context:
Hello, I am working on a Ionic application (made in Typescript). In this application, I control a wifi camera via HTTP Request to the IP (http://192.72.1.1/myCommand to be precise).
Main actions I do with the camera:
Start recording
Stop recording
Get videos list
Download a video
When I use the Ionic DevApp:
With the Ionic DevApp, everything works perfectly, I can do all mains actions without a problem.
When I compile the application on IOS:
I compile with the command ionic cordova build ios --prod, then I archive with Xcode and send it to the AppStore to test it with Test Flight.
I got no errors while compiling / archive the application. But when I try it on my iPhone, I can start / stop recording, but can't download the video.
Problem:
Some commands are not working, but I don't know if it is getting the list or downloading the video, I have no logs. I don't understand why some commands are working but others no.
IOS is blocking download requests? How to solve my problem?
Notes:
I already tried all basic things like delete the IOS platform, recompile, uninstall, ...
I tried different Ionic HTTP plugins, same problem with all of them.
Some code:
Start / Stop the camera: (it is the same command to start / stop).
startCamera(){
var url = "http://192.72.1.1/changeRecordStatus";
var result = this.http.get(url);
result.subscribe(data => {
console.log("Works");
},
err => {
console.log("Error" + err);
}
);
}
Getting the name of the last video:
getLastVideo(){
var url = "http://192.72.1.1/listVideos";
this.http.get(url, {}, {})
.then(data => {
var xml = data.data
var xmlDOM = new DOMParser().parseFromString(xml, 'text/xml');
var temp = this.xmlToJson(xmlDOM); // function that convert XML to JSON
var resultArray = Object.keys(temp).map(function(i){
let ite = temp[i];
return ite;
});
resultArray = resultArray[0]['file'].reverse();
this.lastVideo = resultArray[0]['name']; // lastVideo is a global variable
},
(error) =>{
console.log("Error while getting the name of the last video" + error);
});
}
Downloading the file from the camera:
downloadFileFromCamera() {
this.getLastVideo();
var basename_file = this.lastVideo;
var url = "http://192.72.1.1" + basename_file;
this.fileTransfer.download(encodeURI(url), this.file.dataDirectory + '/videos/' + basename_file, true).then((entry) => {
this.video[this.counterVideos] = entry; // video is a global array
this.counterVideos +=1;
}, (error) => {
console.log("Error while downloading the last video" + error);
});
}
If someone knows how to solve my problem, I would be so grateful! Thanks in advance.
I have used cordova filetransfer plugin. I am uploading a file using fileTransfer plugin's upload function.
The problem is that upload works synchronously and application UI freezes while the file is being uploaded by this plugin.
I want the file upload to run asynchronously and user should be able to interact on UI while upload is in progress.
My cordova application is targeted for iOS and Windows.
I have used cordova filetransfer plugin. I am uploading a file using fileTransfer plugin's upload function.
The problem is that upload works synchronously and application UI freezes while the file is being uploaded by this plugin.
I want the file upload to run asynchronously and user should be able to interact on UI while upload is in progress.
My cordova application is targeted for iOS and Windows.
My javascript function which calls the cordova file-transfer plugin is as below:
var uploadVideo = function(path) {
//UPLOAD VIDEO TO SERVER
var fileURL = path;
var win = function(r) {
console.log("Code = " + r.responseCode);
};
var fail = function(error) {
console.log("An error has occurred: Code = " + error.code);
};
var options = new FileUploadOptions();
options.fileKey = "file";
options.fileName = fileURL.substr(fileURL.lastIndexOf('/') + 1);
options.mimeType = "text/plain";
var params = {};
params.value1 = "test";
params.value2 = "param";
options.params = params;
var ft = new FileTransfer();
ft.onprogress = function(progressEvent) {
if (progressEvent.lengthComputable) {
var perc = Math.round(progressEvent.loaded / progressEvent.total * 100);
$('progress').val(perc);
}
};
ft.upload(fileURL, encodeURI("http://<serverpath>/<endpoint>"), win, fail, options);
};
As soon as this script/function is invoked, user is unable to interect with html page. Page kind of freezes and user can't input any text in text boxes or any other UI interaction.
I'm using the cordova screenshot plugin : https://github.com/gitawego/cordova-screenshot to take a screenshot in my iPhone using this code :
navigator.screenshot.save(function (error, res) {
if (error) {
console.log('Screenshot error');
console.error(error);
} else {
console.log('screenshot ok', res.filePath);
}
}, 'jpg', 50, 'project-X-result');
It seems to work (i have no error) but I can't find the screenshot in the Photos Library. Is it possible to save it in this library?
How should I do? Using another plugin to move the file? (where should it be moved exactly?) Editing the plugin to save it directly in the library? (where should it be saved exactly?)
I just ran through the same problem. It took several days but I figured out how to do it.
It does involve another plugin Canvas2Image plugin. I didn't think it would work, but I was desperate and it did work in the end. Here's how I did it.
If you are getting the console.log for screenshot ok, then you are in good shape. The next thing you will need to do is install Canvas2Image with your CLI like so:
cordova plugin add https://github.com/devgeeks/Canvas2ImagePlugin.git
(or replace 'cordova' with 'phonegap' if you use that instead.)
Next, you will need to add a function (in this case saveImageToPhone()) that calls the plugin you just added to your project. This function will be called from your navigator.screenshot.save() function you already have. We will add that function call to your screenshot.save success block, right after the console.log line.
The key here is using that filePath property that we get back in the success block; That's our absolute path to the image we just saved to the temp folder in iOS. We will simply pass that path to the second function and let it do its work.
Here's those two functions from my code:
function saveScreen(){
navigator.screenshot.save(function(error,res){
if(error){
console.error(error);
}else{
console.log('ok',res.filePath);
var MEsuccess = function(msg){
console.info(msg);
} ;
var MEerror = function(err){
console.error(err);
};
saveImageToPhone(res.filePath, MEsuccess, MEerror);
}
},'jpg',90);
}
function saveImageToPhone(url, success, error) {
var canvas, context, imageDataUrl, imageData;
var img = new Image();
img.onload = function() {
canvas = document.createElement('canvas');
canvas.width = img.width;
canvas.height = img.height;
context = canvas.getContext('2d');
context.drawImage(img, 0, 0);
try {
imageDataUrl = canvas.toDataURL('image/jpeg', 1.0);
imageData = imageDataUrl.replace(/data:image\/jpeg;base64,/, '');
cordova.exec(
success,
error,
'Canvas2ImagePlugin',
'saveImageDataToLibrary',
[imageData]
);
}
catch(e) {
error(e.message);
}
};
try {
img.src = url;
}
catch(e) {
error(e.message);
}
}
Now just call the first function from wherever you wish.
If it works, you'll get a console.log right after your filePath readout that says
IMAGE SAVED!
Be careful, you might overwrite the same screenshot if you use a name as a screenshot.save parameter (after your jpg and quality parameters). My app needs to save different screenshots and have them all available later; by removing the name parameter and allowing the OS to name the file I was able to achieve just that.
I hope that helps you out, I know it caused me a lot of trouble...
I'm a little confused with the filetransfer method of Cordova for iOS. (I had a version working with Android)
Apparently, I don't set the destination folder properly. target:null Could not create target file Note that I assume that the directory exists as it is created with success earlier in the script.
According to the Cordova documentation, I should use a entry.toURL to get the right path.
function download(filename){
var localPath = rootFS.toURL+'contentImages/'+filename;
var fileTransfer = new FileTransfer();
fileTransfer.download(encodeURI('http://myValidatedSource.com/'+filename),
localpath,
function(entry){
console.log('download completed for '+entry.fullPath);
},
function(error){
console.log(error);
}
);
}
I also tried this:
alert(rootFS.fullPath); ==> "/"
and
alert(rootFS.toURL); ==> "function(){
if (this.nativeURL){
return this.nativeURL;
}
return this.toInternalURL()|| "file://localhost"+this.fullPath";
}"
I was not so far...
var localPath = rootFS().toURL+'contentImages/'+filename;
instead of
var localPath = rootFS.toURL+'contentImages/'+filename;
I've a problem with moving a camera photo to the persistent storage under iOS 7 (Cordova 3.4.0-0.1.3 - File API 1.0.1).
I can capture the photo and when I move the file to the persistent storage it seems that there is no error, I also receive a file path with new_entry.fullPath like /my_folder/12345678.jpg.
But when I append the new image to the body with that url it seems that there is no image (blank image will be added). I've tried it also with "file://" in the url, but this makes no difference.
I'm also a little bit confused, because the new_entry.toURL() method returned an url containing a folder named "temporary" (e.g. cdvfile://localhost/temporary/my_folder/12345678.jpg), but I use the persistent storage. Is that correct under iOS?
This is my relevant code for that function:
var app = {
capturePhoto: function () {
if (!navigator.camera) {
alert('Camera API not supported');
}
navigator.camera.getPicture( app.cameraSuccess, app.cameraError, {
quality: 50,
destinationType: Camera.DestinationType.FILE_URI
});
},
cameraSuccess: function (imageData) {
console.log('cameraSuccess: '+imageData);
app.movePhoto( imageData );
},
movePhoto: function (file){
alert(file);
window.resolveLocalFileSystemURI( file , app.resolveOnSuccess, app.resOnError);
},
resolveOnSuccess: function (entry){
var d = new Date();
var n = d.getTime();
//new file name
var newFileName = n + ".jpg";
var myFolderApp = "my_folder";
window.requestFileSystem(LocalFileSystem.PERSISTENT, 0, function(fileSys) {
fileSys.root.getDirectory( myFolderApp,
{create:true},
function(directory) {
entry.moveTo(directory, newFileName, function(new_entry){
path = new_entry.fullPath;
url = new_entry.toURL();
console.log(path+"\n"+url);
alert( path+"\n"+url );
jQuery('body').append('<img src="'+path+'" />');
}, app.resOnError);
},
app.resOnError);
},
app.resOnError);
},
resOnError: function(error) {
alert('Error '+error.code+': '+error.message);
},
}
27/5/2014 UPDATE: Version 1.1.0 was released since than, therefore no need to use dev branch anymore.
It's a bug in cordova: https://issues.apache.org/jira/browse/CB-6148
It's already fixed in dev branch. You can update to dev branch with those steps:
remove the plugin:
cordova plugin rm org.apache.cordova.file
install the plugin (we have to use the git syntax in this case):
cordova plugin add https://github.com/apache/cordova-plugin-file.git#dev
check the iOS build > Targets > Your app target > Build phases > Compile Sources
add (if not added)
CDVFile.m
CDVLocalFilesystem.m
CDVAssetLibraryFilesystem.m