From my Ionic app, running on iPad, I need to upload a zip file to Node Express.
Below is my code for saving the zip on iPad and posting it to the Express server
//This creates the zip file locally. Zip creation on iPad works fine as I am able to open it.
//Using JSZip to create a zip file. Type is set to blob
var zipFiles = function(filesList, uniqueFilename) {
var zip = new JSZip();
var zipFilesPromises = filesList.map(function (file) {
return $cordovaFile.readAsBinaryString(cordova.file.dataDirectory + $rootScope.username, file)
.then(function (binaryData) {
return zip.file(file, binaryData, { binary: true });
});
});
return Promise.all(zipFilesPromises)
.then(function () {
return zip.generateAsync({ type: "blob" });
})
.then(function (blob) {
return $cordovaFile.writeFile(cordova.file.dataDirectory + $rootScope.username, uniqueFilename, blob, true);
})
.then(function (data) {
return Promise.resolve(data);
})
.catch(function (error) {
console.log('Error while zipping and writing ' + JSON.stringify(error));
})
}
This function is then called from the controller. Upon zip file creation it sends it to the Node server using $cordovaFileTransfer.
return fileAPI.zipFiles(docList, zipFilename)
}).then(function(data) {
var targetPath = cordova.file.dataDirectory + $rootScope.username+ '/'+zipFilename;
var trustHosts = true;
var options = {};
var server = config.nodeServerEndpoint + '/uploadparcel';
return $cordovaFileTransfer.upload(server, targetPath, options, trustHosts);
}).then(function (result) {
console.log("success", result);
}).catch(function(error) {
console.log('Error - '+JSON.stringify(error));
});
On the Node server side, below code is saving the zip file
function uploadZip(request, response) {
var size = 0;
var data = new Buffer('');
request.on('data', function (chunk) {
data = Buffer.concat([data, chunk]);
});
request.on('end', function () {
request.rawBody = data;
fs.writeFile('userdata/abc123.zip', request.rawBody, 'binary', function(err){
if (err) {
throw err;
}
})
response.end("Thanks");
});
request.on('error', function(e) {
console.log("ERROR ERROR: " + e.message);
});
}
This code creates a corrupted zip file when called from ionic app. However, if I attach a file in Postman and post to this URL then a valid zip file is created.
So, I suspect it could be something to do with how I am creating my zip file on Ionic (as a blob) and seems that node code is not able to understand that.
In nutshell, zip being created in the device is valid (as I am able to open it) and the zip saved on the node server is also valid when called from Postman. However, when zip created in ionic is send to node, then node saves a corrupted zip file.
Is there something else that I need to be doing on either the node or the ionic side to make it work.