How to set password to a zip file using Jquery - javascript

Here is my code.I am able to download the zip file, but now i want to set a password to it using javascript/jquery.
function saveAsZip(fileContents, fileName) {
var zip = new JSZip();
zip.file(fileName, fileContents);
var content = zip.generate();
var link = document.createElement('a');
var linkName = fileName.replace('.XML', '')
link.download = linkName + '.zip';
link.href = "data:application/zip;base64," + content;
link.click();
}

Actually, this is just not possible so far, as stated here:
https://github.com/Stuk/jszip/issues/291
If you use node.js on linux, this question might be a way to achieve it: How do I password protect a zip file in Nodejs?

I ended up using Ionic.Zip in Dot Net. Here is my html and javascript code
<div>
<input type="password" id="pass" placeholder="Set Password" />
<button type="submit" class="cutomDownloadCCDA">Zip</button>
</div>
<script>
$('.cutomDownloadCCDA').click(function(e) {
//window.location.href = "Home/Zip";// Simple Way
var password = $('#pass').val();
$('#downloadFrame').remove(); // This shouldn't fail if frame doesn't exist
$('body').append('<iframe id="downloadFrame" style="display:none"></iframe>');
$('#downloadFrame').attr('src', '/Home/Zip?password=' + password);
});
</script>
Here is the action Method of MVC
public void Zip(string password)
{
using (ZipFile zip = new ZipFile())
{
string xml = "Your XML Data";
var newStream = new MemoryStream();
var newWriter = XmlWriter.Create(newStream);
newWriter.WriteRaw(xml);
newStream.Position = 0;
newWriter.Flush();
newStream.Seek(0, SeekOrigin.Begin);
// Ist File
ZipEntry e = zip.AddEntry("test.xml", newStream);
e.Password = password;
e.Encryption = EncryptionAlgorithm.WinZipAes256;
// 2nd File
//ZipEntry f2 = zip.AddEntry("test1.xml", newStream);
//f2.Password = "456";
//f2.Encryption = EncryptionAlgorithm.WinZipAes256;
Response.ContentType = "application/zip";
Response.AddHeader("Content-Disposition", "attachment;filename=somefile.zip");
zip.Save(Response.OutputStream);
}
}

Related

Javascript: Upload a file from inside a tar file

I have an HTML form that is used to upload a file to the server. This works correctly but now I am trying to expand the capability such that I select a tar file that consists of two binary files. Then untar the files and based on certain conditions either upload the first or the second file.
This is what I have done so far
use FileReader to read the tar file as ByteArray
use untar from js-untar to untar both file
I need help to figure out how to take the ByteArray for either files and add then to the FormData so that I can upload them.
Any help would be appreciated.
Here are snippets from my code
HTML Form
<form id="upform" enctype="multipart/form-data"
action="cgi-bin/upload2.cgi">
Firmware file: <input id='userfile' name="userfile" type="file" width=50 >
<input type
="submit" name="submitBtn" value="send file">
</form>
Untar code
function sendData() {
var formData = new FormData(form);
var action = form.getAttribute('action');
filesize = file.files[0].size;
var reader = new FileReader();
reader.onload = function() {
untar(reader.result).then(
function (extractedFiles) { // onSuccess
console.log('success');
formData.delete('userfile');
var reader2 = new FileReader();
reader2.onload = function() {
formData.append('userfile', reader2.result);
upload(formData);
}
var blob = new Blob([extractedFiles[0]], {type : 'multipart/form-data'});
reader2.readAsDataURL(blob);
// var f = URL.createObjectURL(blob);
},
function (err) {
console.log('Untar Error');
}
)
};
reader.readAsArrayBuffer(file.files[0]);
return;
}
function upload(formData) {
var action = form.getAttribute('action');
reqUpload.open('POST', action, true);
reqUpload.onreadystatechange = uploadState;
document.body.style.cursor = "wait";
var ld = document.getElementById("load");
ld.classList.add("loader");
reqUpload.send(formData);
document.getElementById('progress').style.display = "block";
progTimer = setInterval(ping, 10000);
uploadStarted = true;
return;
}

Opening a msg file into Outlook though JavaScript

I have a msg file stored in a Database and want a user to be able to open outlook from a browser with that file.
Until now a user can only save/open this msg file through that code:
window.DownloadFile = function (myFile) {
var data = myFile.Base64String;
var filename = myFile.FileName;
if (clientType === 'Windows') {
var file = dataURItoBlob(data);
if (window.navigator.msSaveOrOpenBlob)
window.navigator.msSaveOrOpenBlob(file, filename);
}
else {
var a = document.createElement("a");
a.href = data;
a.download = filename;
document.body.appendChild(a);
a.click();
document.body.removeChild(a);
}
}
But I want the user to be able to open Outlook with that file.
Thanks in Advance
Lerxx
You can save the .msg file on the disk and then run this file using the following code:
<script language="JavaScript" type="text/javascript">
MyObject = new ActiveXObject( "WScript.Shell" )
function RueMsg()
{
MyObject.Run("file:///filepath.msg") ;
}
</script>
Due to the fact that Outlook is a singleton, the message will be opened even if it is already running on the system.

Angular JS app: save excel file and show it later

In my application (developed with AngularJS framework) I must create and download an excel file in client side (Javascript language). To do this, I have this code
var form = document.createElement('form');
form.action = 'download';
form.method = 'POST';
form.style.display = 'none';
var inputsrtoken = document.createElement('input');
inputsrtoken.style.setAttribute("width", "0");
inputsrtoken.style.setAttribute("diplay", "none");
inputsrtoken.style.setAttribute("visibility", "hidden");
inputsrtoken.type = 'text';
inputsrtoken.name = 'srtoken';
inputsrtoken.value = token;
var inputData = document.createElement('input');
inputData.style.setAttribute("width", "0");
inputData.style.setAttribute("diplay", "none");
inputData.style.setAttribute("visibility", "hidden");
inputData.type = 'text';
inputData.name = 'inputRicalcolo';
inputData.value = JSON.stringify(excelData);
var submit = document.createElement('input');
submit.type = 'submit';
submit.id = 'submitProject';
form.appendChild(inputsrtoken);
form.appendChild(inputData);
form.appendChild(submit);
document.body.appendChild(form);
$('#submitProject').click();
document.body.removeChild(form);
Where in variable excelData are included some usefull information for the generation of excel file.
Server side, I have this code (in the download servlet)
if (Base64.isArrayByteBase64(excelin.getBytes("UTF-8"))) {
excelin = new String(Base64.decodeBase64(excelin.getBytes("UTF-8")), "UTF-8");
}
bpdf = createExcelRicalcolo(excelin);
String chiave = request.getParameter("chiave");
DateFormat formatter = new SimpleDateFormat("ddMMyyyy-HHmm");
String format = formatter.format(new Date());
String filename = "RICALCOLO_ONLINE_"+chiave +"_"+ format + ".xls";
byte[] b = bpdf;
if (b != null) {
int length = b.length;
ServletOutputStream op = resp.getOutputStream();
resp.setContentType("application/ms-excel");
resp.setContentLength(length);
resp.setHeader("Content-Disposition", "attachment; filename=" + filename);
resp.setHeader("Expires", "0");
resp.setHeader("Cache-Control", "must-revalidate, post-check=0, pre-check=0");
resp.setHeader("Pragma", "public");
op.write(b);
op.flush();
op.close();
}
It works great!
But now, this is my question: is it possible to generate the file, without downloading it, but only to save it (maybe with a service in javascript) for a subsequent download request?
In fact, my goal is the following: I would like to generate an excel file (and not show to the user), save it on a DB2 column as a CLOB and only then (by pressing for example another button on the app) give the user the possibility to download it.
Do you believe it is possible to do such a thing without upsetting the logic of the code?
Saving the file as a CLOB will be the following problem to be framed.
Grace to anyone who will try to help me.

Empty excel file is uploaded in JavaScript

I'm trying to upload and download the excel file in a single click operation. I'm calling two APIs in a single operation. The download operation is working fine. But during file upload, an empty excel file is being uploaded with the exact file-name. This is the server side code
Excel Duplicates Remover in JAVA. The server-end works fine. And this is the client-side code.
<!DOCTYPE html>
<html>
<body>
Select a file: <input type="file" id="file" accept=".csv, .xls, application/vnd.openxmlformats-officedocument.spreadsheetml.sheet, application/vnd.ms-excel" multiple size="50"/><br>
Keyword:<input type="text" id="columnHeading"/><br>
<button type="button" onclick="downloadDoc()">Request data</button>
<script>
function downloadDoc(){
var fileTab = document.getElementById("file");
var columnHeading = document.getElementById("columnHeading");
if('files' in fileTab) {
if(fileTab.files.length == 1) {
var url = 'http://localhost:8080/excel-duplicate-remover/rest/fileService/';
var uploadUrl = url + "upload";
var file=fileTab.files[0];
var formData = new FormData();
formData.append("columnHeading",columnHeading);
formData.append("file",file);
var xhr = new XMLHttpRequest();
xhr.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
var response = JSON.parse(this.responseText);
var path = response.path;
var downloadUrl = url + 'downloadFile?fileName=' + path;
downloadFile(downloadUrl);
}
};
xhr.open("POST", uploadUrl);
xhr.send(formData);
}else{
console.log("file not present");
}
}
}
function downloadFile(filename) {
console.log("filename"+filename);
var link = document.createElement('a');
// Add the element to the DOM
link.setAttribute("type", "hidden"); // make it hidden if needed
link.href = filename;
link.download;
document.body.appendChild(link);
link.click();
link.remove();
}
</script>
</body>
</html>
Why is the file being uploaded as an empty excel file?

HTML5 File Handeling in JavaScript?

What techniques are used to load a file (ASCII or Binary) into a variable (var file = "text";) in JavaScript?
You want to use the new HTML5 File API and XMLHttpRequest 2.
You can listen to files being either selected via a file input or drag & dropped to the browser. Let's talk about the input[type="file"] way.
<input type="file">
Let's listen for files being selected.
var input; // let input be our file input
input.onchange = function (e) {
var files = input.files || [];
var file = files[0];
if (file) {
uploadFile(file);
}
};
What you need to create a real multipart file upload request is a FormData object. This object is a representation of the body of your HTTP POST request.
var uploadFile = function (file) {
var data = new FormData();
data.append('filename', file);
// create a HTTP POST request
var xhr = new XMLHttpRequest();
xhr.open('POST', './script.php', true);
xhr.send(data);
xhr.onloadend = function () {
// code to be executed when the upload finishes
};
};
You can also monitor the upload progress.
xhr.upload.onprogress = function (e) {
var percentage = 100 * e.loaded / e.total;
};
Ask if you need any clarification.
If you want to use the new HTML5 way this is how I did it... keep in mind that I made a method called File() and this is not a true HTML5 method its a wrapper to it... this might be changed in the future so beware (maybe rename it).
HTML:
<html>
<body>
<input type="file" id="files" name="file"/>
<button onclick="load()">Load File</button><br /><br />
<div id="content"></div>
<script>
function load() {
var fileObj = document.getElementById("files");
var fp = new File(fileObj);
fp.read(callback);
}
function callback(text) {
var content = document.getElementById("content");
content.innerHTML = text;
}
</script>
</body>
</html>
JavaScript:
function File(name) {
this.name = document.getElementById(name) ? document.getElementById(name).files : name.files ? name.files : name;
}
// Reads the file from the browser
File.prototype.read = function(callback) {
var files = this.name;
if (!files.length) {
alert('Please select a file!?');
return;
}
var file = files[0];
var reader = new FileReader();
reader.onloadend = function(evt) {
if (evt.target.readyState == FileReader.DONE) { // DONE == 2
callback(evt.target.result);
}
};
var data = file.slice(0, file.size);
reader.readAsBinaryString(data);
}
Have the JavaScript being generated inside a PHP or Rails (or whatever you use server-side) and include the file.
<?php
$my_string = file_get_contents('/path/to/file.txt');
?>
<script>
var my_js_file_string = "<?php echo $my_string; ?>";
...
document.write(my_js_file_string);
</script>

Categories