简体   繁体   English

如何从Javascript中的Base64字符串获取ZIP文件?

[英]How to get the ZIP file from Base64 string in Javascript?

I am trying to get the compressed ZIP file back in Javascript. 我正在尝试用Javascript重新获得压缩的ZIP文件。 I am able to convert the zip file into Base64 String format. 我可以将zip文件转换为Base64 String格式。 (Zip file is in Server) (压缩文件在服务器中)

Here is my try (at Server Side) 这是我的尝试(在服务器端)

System.IO.FileStream fs = new System.IO.FileStream(SourceFilePath + "Arc.zip", System.IO.FileMode.Open);
Byte[] zipAsBytes = new Byte[fs.Length];
fs.Read(zipAsBytes, 0, zipAsBytes.Length);
String base64String = System.Convert.ToBase64String(zipAsBytes, 0, zipAsBytes.Length);
fs.Close();

if (zipAsBytes.Length > 0)
{
    _response.Status = "ZipFile";
    _response.Result = base64String;
}

return _json.Serialize(_response);

This part of code returns the JSON data. 这部分代码返回JSON数据。 This JSON data includes the Base64 string. 此JSON数据包含Base64字符串。 Now what i want to do is to get the original zip file from Base64 string. 现在,我要做的是从Base64字符串获取原始zip文件。 I searched over the internet but not get the idea. 我通过互联网搜索,但不知道。

Is this achievable ?. 这是可以实现的吗?

It is achievable. 这是可以实现的。 First you must convert the Base64 string to an Arraybuffer. 首先,您必须将Base64字符串转换为Arraybuffer。 Can be done with this function: 可以使用以下功能完成:

function base64ToBuffer(str){
    str = window.atob(str); // creates a ASCII string
    var buffer = new ArrayBuffer(str.length),
        view = new Uint8Array(buffer);
    for(var i = 0; i < str.length; i++){
        view[i] = str.charCodeAt(i);
    }
    return buffer;
}

Then, using a library like JSZip , you can convert the ArrayBuffer to a Zip file and read its contents: 然后,使用类似JSZip的库,您可以将ArrayBuffer转换为Zip文件并读取其内容:

var buffer = base64ToBuffer(str);
var zip = new JSZip(buffer);
var fileContent = zip.file("someFileInZip.txt").asText();
  • JavaScript does not have that functionality. JavaScript没有该功能。
  • Theoretically there can be some js library that does this, but it's size probably would be bigger than the original text file itself. 从理论上讲,可以有一些js库来执行此操作,但是它的大小可能会比原始文本文件本身大。
  • You can also enable gzip compression on your server, so that any output text gets compressed. 您还可以在服务器上启用gzip压缩,以便压缩任何输出文本。 Most of the browsers would then uncompress the data upon its arrival. 然后,大多数浏览器会在数据到达时解压缩数据。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM