Download only new files on an Ionic app? - angularjs

I want to download a file from a server only if the file is new. For example, by checking the file modified date. I am using the below code to download the file, but I am stuck where I need to compare the files before downloading. Can anyone please give me a solution for this.
.factory('fileDownloadService',['$cordovaFileTransfer', function($cordovaFileTransfer){
return{
fileDownload:function(){
// File for download
var url = "http://www.xxxxx/file-to-download.json";
// Get file name only
var filename = url.split("/").pop();
// Save location
var targetPath = cordova.file.externalRootDirectory + filename;
$cordovaFileTransfer.download(url, targetPath, {}, true).then(function (result) {
console.log('Download Successful');
}, function (error) {
console.log('Download Error');
}, function (progress) {
// Progress handling
});
}
}}])
Appreciate your help. Thank you

Related

save video files in iOS gallery using Cordova plugin

I am trying to save a video from a URL in my iOS device using a ionic Cordova file transfer .
var fileTransfer = new FileTransfer();
var uri = "https:xyz.abc/demo.mp4";
var fileURL = cordova.file.documentsDirectory + 'demoRename.mp4';
fileTransfer.download(
uri, fileURL, 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("download error code" + error.code);
}
);
I can see the downloaded path as below using console log.
[Log] download complete: file:///var/mobile/Containers/Data/Application/EB4C2F9A-9C4D-4CA6-BED0-D83B7D4CBDE1/Documents/demoRename.mp4
But I can not see the downloaded video file in my gallery or in photos ,Where can I find them or am I doing it right?
you will need to save the video to gallery then you will able to see the downloaded video in the gallery.
please use the photo library plugin and follow the below link.
https://github.com/terikon/cordova-plugin-photo-library
use the below code may be it will helpful to you.
//based on device type choosing the location to save the video
if (ionic.Platform.isIOS()) {
var path = cordova.file.documentsDirectory;
var filename = "preview.mp4";
} else {
var path = cordova.file.externalRootDirectory;
var filename = "preview" + $filter('date')(new Date(), "yyyy-MM-dd HH:mm:ss") + ".mp4";
}
//Creating directory to save video in the device
$cordovaFile.createDir(path, "dir", true).then(function(success) {
var targetPath = path + "dir/" + filename;
var trustHosts = true;
var options = {};
//Downloading the file from URL.
$cordovaFileTransfer.download("video URL", targetPath, options, trustHosts).then(function(result) {
//Once downloaded the file calling function to add the video to photo library
if (ionic.Platform.isIOS()) {
function savelibrery() {
cordova.plugins.photoLibrary.saveVideo(targetPath, album, function(success) {}, function(err) {
if (err.startsWith('Permission')) {
cordova.plugins.photoLibrary.requestAuthorization(function() {
savelibrery();
}, function(err) {
$ionicLoading.hide();
$cordovaToast.show("Oops! unable to save video, please try after sometime.", "long", "center");
// User denied the access
}, // if options not provided, defaults to {read: true}.
{
read: true,
write: true
});
}
});
}
savelibrery()
} else {
//add refresh media plug in for refresh the gallery for android to see the downloaded video.
refreshMedia.refresh(targetPath);
}
$ionicLoading.hide();
$cordovaToast.show("Vidoe saved successfully", "long", "center");
}, function(error) {
$ionicLoading.hide();
$cordovaToast.show("Oops! unable to save video, please try after sometime.", "long", "center");
}, function(progress) {
$scope.downloadProgress = (progress.loaded / progress.total) * 100;
$cordovaToast.show("In progress", "short", "center");
});
}, function(error) {
//alert(JSON.stringify(error));
$ionicLoading.hide();
$cordovaToast.show("Oops! unable to save video, please try after sometime.", "long", "center");
});

nodejs write simple image blob - Upload.dataUrltoBlob

Simple question. How do I save a image blob in Nodejs from angular.
AngularSide:
$scope.upload = function (dataUrl, picFile) {
Upload.upload({
url: 'http://test.dev:3000/register/user/uploads',
data: {
file: Upload.dataUrltoBlob(dataUrl, picFile.name)
},
}).then(function (response) {
$timeout(function () {
$scope.result = response.data;
});
}, function (response) {
if (response.status > 0) $scope.errorMsg = response.status
+ ': ' + response.data;
}, function (evt) {
$scope.progress = parseInt(100.0 * evt.loaded / evt.total);
});
}
nodejs side: Do I need middleware here? if so which one should I use?
router.post('/user/uploads', multipartMiddleware, function(req, resp) {
var newPath = "/Users/testUser/test_hold_files/" + req.files.file.originalFilename;
fs.writeFile(newPath, req.files.file, function(err) {
if (err) {
console.log("Data Error ");
return console.error(err);
}
});
res.status(200).jsonp({status: "status: success "});
});
right now this just writes out the file with correct name but its empty.
You used to be able to access the uploaded file through req.files.imageName and then you would fs.readFile from tmp and write it permanently, which is no longer the case in express 4.0
In Express 4, req.files is no longer available on the req object by default. To access uploaded files on the req.files object, use multipart-handling middleware like busboy, multer, formidable, multiparty, connect-multiparty, or pez.
Soooooooo, you can feel free to use which ever one of those middlewares names above and then follow their API for dealing with uploaded files like images. Hope this helps, enjoy.
Ok,
After a long time of messing with this stuff. I found an answer. It does load the file in my folder.
I feel this is only partial since it does not resize the actual file smaller. It is what is selected with https://github.com/danialfarid/ng-file-upload. I used the
Upload.upload({
url: 'http://test.dev:3000/register/user/uploads',
data: {
file: Upload.dataUrltoBlob(dataUrl, picFile.name)
},
This did zoom into the file on selected image. It did not make the actual file size smaller. I am still looking into this issue.
var formidable = require('formidable'),
util = require('util'),
fs_extra = require('fs-extra');
This is my post to accept images.
router.post('/user/uploads', function (req, res){
var form = new formidable.IncomingForm();
form.parse(req, function(err, fields, files) {
res.writeHead(200, {'content-type': 'text/plain'});
res.write('received upload:\n\n');
res.end(util.inspect({fields: fields, files: files}));
});
form.on('end', function(fields, files) {
/* Temporary location of our uploaded file */
var temp_path = this.openedFiles[0].path;
/* The file name of the uploaded file */
var file_name = this.openedFiles[0].name;
/* Location where we want to copy the uploaded file */
var new_location = "/Users/testUser/test_hold_files/";
fs_extra.copy(temp_path, new_location + file_name, function(err) {
if (err) {
console.error(err);
} else {
console.log("success!")
}
});
});
});
I have also noticed that I can view the file in chrome but not load it into gimp. Gimp gives me a file error.
Small steps I guess.
Maybe Datsik can give us some insight on what is going on here.
https://stackoverflow.com/users/2128168/datsik
Phil

Cordova File Plugin Has Wrong Directory

So I am building a cordova/phonegap app in angularjs 1 and I'm trying to save and read from a file called calendar.txt in the app's private directory/sandbox and can't.
My console logs while debugging show that there are no errors and the file is being created if it doesn't exist, and is being read correctly. However that is not the case. When I build and run on my device, the data is not saved. Also no file is created in the location specified.
I console logged the path it was trying to use and this is it:
file:///data/data/com.adobe.phonegap.app/files/calendar.txt
Here is the code I am using to open the file:
$rootScope.openFile = function(){
var pathToFile = cordova.file.dataDirectory + "calendar.txt";
console.log('path = ' + pathToFile);
window.resolveLocalFileSystemURL(pathToFile,
function(fileEntry){
fileEntry.file(function (file) {
var reader = new FileReader();
reader.onloadend = function (e) {
$rootScope.calendar = JSON.parse(this.result);
console.log('file opened');
console.log(JSON.parse(this.result));
};
reader.readAsText(file);
}, function(error){});
}, function(error){
if(error.code == FileError.NOT_FOUND_ERR){
$rootScope.calendar = new Year();
console.log('no file found so it was created');
$rootScope.saveFile();
}
else{
console.log(error);
}
});
};
And here is the code for my save the file:
$rootScope.saveFile = function(){
var data = JSON.stringify($rootScope.calendar, null, '\t');
var fileName = "calendar.txt"
window.resolveLocalFileSystemURL(cordova.file.dataDirectory,
function(directoryEntry){
directoryEntry.getFile(fileName, { create: true },
function (fileEntry) {
fileEntry.createWriter(
function (fileWriter) {
var blob = new Blob([data], { type: 'text/plain' });
fileWriter.write(blob);
console.log('file saved');
},
function (error){});
},
function (error){}
);
},
function(error){
console.log("Saving Error: Error during finding directory", error.message);
}
);
};
I have used this tutorial to get this far: Cordova File Plugin Tutorial
What am I doing wrong?
I assume that you are facing this issue in Android as i too faced the same. As per my understanding and googling, in android (atleast in android 5) you cant write in application data directory unless the phone is rooted. So you may have to use externalRootDirectory instead.
eg: window.resolveLocalFileSystemURL(cordova.file.externalRootDirectory,successCallback, errorCallback);
Hope it helps.

Downloading a file from MongoDB to local filesystem

I have asked various questions and got only limited answers and it has gotten me this far:
Mongoose code :
app.get('/Download/:file(*)', function (req, res) {
grid.mongo = mongoose.mongo;
var gfs = grid(conn.db);
var file = req.params.file
var fs_write_stream = fs.createWriteStream('Program.cs');
var readstream = gfs.createReadStream({ filename: file });
readstream.pipe(fs_write_stream);
res.download(__dirname+'/Program.cs', 'Solution.cs', function (err) {
if (err) throw err;
else console.log("check console");
});
})
Angular code:
$scope.Download = function () {
$http.get(url + "/Download/"+"Program.cs")
.success(function (res) {
console.log(res);
})}
When I open my console angular just returns a blank line, when i look into the network aspect the header sais this:
I want to be able to store this file to my local file system to a path that I want to be able to choose myself. PLEASE help me out, I'm desperate, I have looked EVERYwhere for a solution, thank you very much in advance!
Try this instead of your client side download attempt:
<a class="btn" href="/Download/Program.cs" download>

Zip generated by EasyZip is not working properly

I have generated a zip file using Easyzip. I can open it directly from download folder.But when try to open it after downloading, I am getting this error:- 'error occurred while extracting files'.
This my backend code :-
var zip2 = new EasyZip();
zip2.zipFolder('./downloads/'+application._id,function(){
zip2.writeToFile('./downloads/'+application._id+'.zip');
res.setHeader('Content-disposition', 'attachment; filename='+application._id+'.zip');
res.setHeader('Content-type', 'application/zip');
var fs = require('fs');
var filestream = fs.createReadStream('./downloads/'+application._id+'.zip');
filestream.pipe(res);
});
});
My angular.js code
$http.post('/download/archive/' + stateParams._id, {year: year}).success(function (data) {
var file = new Blob([data], {type: 'application/zip'});
console.log(file)
saveAs(file, 'application.zip');
});
Please help me to solve these. Thanks in advance.
I had the same problem and was able to solve it by using:
{responseType:'arraybuffer'} in the $http.post() request.
For more details check: how to download a zip file using angular as well as AngularJS: Display blob (.pdf) in an angular app
Solved issue by using node-native-zip module.
Here is my backend code
var zip = require("node-native-zip");
var files = []
files.push({name:application._id+'.pdf',path:'./downloads/'+vetting_id+application._id+'.pdf'}); //push all the files along with its name and path
var archive = new zip();
archive.addFiles(files, function (err) {
if (err) return res.status(400).send({
message: errorHandler.getErrorMessage(err)
});
var buff = archive.toBuffer();
var fs = require('fs');
fs.writeFile('./downloads/'+ vetting._id+'.zip', buff, function () {
console.log("Finished");
var filestream = fs.createReadStream('./downloads/'+vetting._id+'.zip');
filestream.pipe(res);
});

Resources