Zip generated by EasyZip is not working properly - angularjs

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);
});

Related

I cant download a zip file in AngularJS (from Laravel response)

I am trying to download a zip file from a Laravel API using Angular JS. I do not believe the issue is from Laravel.
Basically when the response comes and the download trigger is made it does not know its a .zip file, however the file itself is good. But then when I manually add the .zip extension in Angular JS in the file name the browser advises its a corrupt file.
If I do not add the extension, it downloads fine, and then if i rename the file with no extension in Windows and change it to test.zip it works perfectly as a zip file. This is how I know the data is good.
I have tried arraybuffer responseType and blob. With blob I am getting the download trigger, with arraybuffer nothing is happening (including no console errors).
Here is my JS controller code:
vm.downloadSelectedFiles = function() {
vm.selectedFiles = [];
angular.forEach(vm.fileDownloadList, function(value,index) {
if(value==1) {
vm.selectedFiles.push(index);
}
});
Data.downloadSelectedFiles(vm.selectedFiles,vm.stationIDToLookUp)
.then(function (data) {
var url = $window.URL || $window.webkitURL;
vm.fileUrl = url.createObjectURL(data.data);
var a = document.createElement("a");
a.href = vm.fileUrl;
a.download = 'test.zip';
//a.download = 'test';
a.click();
}).catch(function (err) {
});
}
Here is my JS service code
downloadSelectedFiles: function downloadSelectedFiles(selectedFiles,stationID) {
var apiBase = apiUrl + 'download-selected-files';
var config = {
//responseType: 'arraybuffer'
responseType: 'blob'
};
var data = {
selectedFiles: selectedFiles,
stationID: stationID
}
return $http.post(apiBase, data, config);
}
And just in case there is something relevant about the response from the API. Here is my Laravel code
public function downloadSelectedFiles(PublishDataRequest $requestData) {
return response()->file(storage_path() . '/app/files/test.zip');
}
Try setting the MIME type to application/zip:
Data.downloadSelectedFiles(vm.selectedFiles,vm.stationIDToLookUp)
.then(function (response) {
var blob = response.data;
var zipBlob = new Blob([blob], { type: "application/zip" });
var url = $window.URL || $window.webkitURL;
vm.fileUrl = url.createObjectURL(zipBlob);
var a = document.createElement("a");
a.href = vm.fileUrl;
a.download = 'test.zip';
//a.download = 'test';
a.click();
}).catch(function (response) {
console.log("ERROR", response);
throw response;
});

File download using SuperAgent

I'm trying to download files from server using SuperAgent. Please find the code below.
downloadDocument(fileIdMongo) {
var request = require('superagent');
var apiBaseUrl = "api/downloadDoc";
var self = this;
var req = request.get(apiBaseUrl);
req.query({ id: fileIdMongo })
req.end(function(err, res) {
if (err) {
console.log("error ocurred");
} else {
var blob = new Blob([res.text], {
type: 'text/csv/jpeg/jpg/png/pdf/docx/doc;charset=utf8;'
});
var element = document.createElement('a');
document.body.appendChild(element);
element.download = "Capture.PNG";
element.href = window.URL.createObjectURL(blob);
element.style.display = '';
element.click();
}
});
}
I'm trying to get a .png file from the server. I tested server with PostMan rest client. I'm able to get the .png file. But the file is not visible when using SuperAgent.
Use the below line of code in the else part.
window.location= 'api/CommercialInvoice?item=' + item.id,'';
element.click();

MEAN js download file from system path

I want to implement feature in MEANJS project to download mp3 files from system path
Example: /usr/local/setup/file.mp3
I want to apply security checks for valid user and allow user to download mp3 files.
Is there any other way which can be used to download files with security?
We can use below node js function
var path = require('path');
var fs = require('fs');
app.get('/api/download-music', function(req, res){
var filename = "file.mp3";
var filePath = path.join("/usr/local/setup/", filename);
var stat = fs.statSync(filePath);
res.writeHead(200, {
'Content-Type': 'audio/mp3',
'Content-Length': stat.size,
"content-disposition":"attachment; filename="+filename
});
var readStream = fs.createReadStream(filePath);
readStream.on('data', function(data) {
var flushed = res.write(data);
// Pause the read stream when the write stream gets saturated
if(!flushed)
readStream.pause();
});
res.on('drain', function() {
// Resume the read stream when the write stream gets hungry
readStream.resume();
});
readStream.on('end', function() {
readStream
.pipe(res);
});
});
}
in above node js code we can apply security checks with session id.
on angular template we can use below html:
Download

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 Mongoose in Angular

I've managed to upload a file and store it in my MongoDB, but now I want to be able to downlaod this file from the same mongoDB. In server-side I'm using the GridFS module in Mongoose to upload and download using the gfs-read/write-stream.
Downlaod code in Mongoose looks like :
app.post('/Download', function (req, res) {
grid.mongo = mongoose.mongo;
var gfs = grid(conn.db);
var readstream = gfs.createReadStream({
filename: 'Program.cs'
});
readstream.pipe(res);
})
In my angular i have this so far:
$scope.Download = function () {
$http.post(url + "/Download")
.success(function (res) {
console.log(res);
})
}
the console.log response is shown here
I want to save this content into a .cs file in my local file system, also want to be able to prompt the user for the download-path, How do I do this?
Try below code
app.post('/Download', function (req, res) {
var filenameId = "";// mention _id value of 'Program.cs'
var filename = 'Program.cs';
var _id = new ObjectID(filenameId );
var gfs = new Grid(conn.db, "yourfile_collection_name");// default value is fs
gfs.get(_id, function(err, data) {
if (err)
throw err;
res.setHeader('Content-Disposition','attachment; filename="' + filename + '"');
res.send(data);
});
};

Resources