这是我的代码。我可以下载zip文件,但现在我想使用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();
}
答案 0 :(得分:3)
实际上,到目前为止,这是不可能的,如下所述:
https://github.com/Stuk/jszip/issues/291
如果你在linux上使用node.js,这个问题可能是实现它的一种方法:How do I password protect a zip file in Nodejs?
答案 1 :(得分:1)
我最终在Dot Net中使用Ionic.Zip
。这是我的html和javascript代码
<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>
这是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);
}
}