简体   繁体   中英

File saving on HTML page using JavaScript

I'm trying to develop SignalR JavaScript client (plain HTML page, which gets live updates from my SignalR backend using JavaScript), and I'm struggling with file pushing problem.

What I'm trying to achieve: Backend does some work and saves results to *.zip file on server, pushes this file to client, HTML page offers operator to save the file. Below there is a C# backend code doing zipping and push.

private void CreateZip()
        {
            if (SdkHub.RR.XMLResults && SdkHub.RR.SaveImages)
            {
                using (var zip = new ZipFile())
                {
                    var mstream = new MemoryStream();
                    mstream.Seek(0, SeekOrigin.Begin);
                    zip.AddDirectory(mydir);
                    zip.Save(mstream);
                    mstream.Position = 0;
                    Clients.All.downloadResult(mstream.ToArray(), myName+".zip");
                }
            }
        }

I've spent some time researching "saving files with JavaScript" and found a solution FileSaver.js , which allows to save generated files. My JavaScript code:

downloadResult: function (result, name) {
            try {
                var blob = new Blob(result, { type: "application/zip" });
                saveAs(blob, name);
            } catch (e) {
                alert(e);
            }
        }

I've figured out, that I SignalR converts byte[] to base64 string , so I've made a little update to my C# :

 var intArray = mstream.ToArray().Select(b => (int)b).ToArray();
 Clients.All.downloadResult(intArray, myName+".zip");

While debugging, I see, that received result parameter in JavaScript is an array, equal to byte[] array in C# , and zip file saving is issued, but unfortunately, it's invalid. When I open it using Notepad++ , I see my array 8513115 ...

Am I doing something wrong? Maybe there are other solutions to achieve my goal?

Thanks in advance!

Update Screenshot from FireBug debugger

FireBug调试器的屏幕截图

Try using Uinit8Array like:

downloadResult: function (result, name) {
  try {
    var u8 = new Uint8Array(result.length);
    for (var i=0; i < result.length; i++) u8[i] = result[i];

      var blob = new Blob(u8, { type: 'application/octet-binary' });
      saveAs(blob, name);
  } catch (e) {
      alert(e);
  }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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