最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Angular 13 - Download file from ByteArray data - Stack Overflow

programmeradmin0浏览0评论

I get a byte[] file from my server with the content of a file. I know the name and the content-type. So far I have tried the following for downloading the file:

const a = document.createElement('a');
document.body.appendChild(a);
a.style.display = 'none';

const file = new Blob([content], {type: 'text/plain'});
const url = window.URL.createObjectURL(file);
a.href = url;
a.download = "test.txt";
a.click();
window.URL.revokeObjectURL(url);

But this solution just downloads a text file with the binary content in it. How can I convert the binary data to the correspondent file type in the client side using JavaScript/Typescript? Thanks!

I get a byte[] file from my server with the content of a file. I know the name and the content-type. So far I have tried the following for downloading the file:

const a = document.createElement('a');
document.body.appendChild(a);
a.style.display = 'none';

const file = new Blob([content], {type: 'text/plain'});
const url = window.URL.createObjectURL(file);
a.href = url;
a.download = "test.txt";
a.click();
window.URL.revokeObjectURL(url);

But this solution just downloads a text file with the binary content in it. How can I convert the binary data to the correspondent file type in the client side using JavaScript/Typescript? Thanks!

Share Improve this question edited Jun 10, 2022 at 10:23 Iñigo asked Jul 17, 2019 at 11:33 IñigoIñigo 2,01610 gold badges31 silver badges60 bronze badges
Add a comment  | 

3 Answers 3

Reset to default 11

You can use file-saver

import { saveAs } from 'file-saver';

const file = new Blob([content], {type: 'text/plain'});
FileSaver.saveAs(file, "test.txt");
saveByteArray(bytes, type) {
  var blob = new Blob([bytes],{type:type});
  var link = document.createElement('a');
  link.href = window.URL.createObjectURL(blob);
  link.download = "fileName";
  link.click();
}

 c#.net:
 public byte[] DocContent { get; set; }

Angular: 
DocContent:ArrayBuffer;

typescript: 
var content= this.base64ToArrayBuffer(response.DocContent);
        var blob = new Blob([content], { type: response.ContentType });

base64ToArrayBuffer(base64: any): ArrayBuffer {
    var binary_string = window.atob(base64);
    var len = binary_string.length;
    var bytes = new Uint8Array(len);
    for (var i = 0; i < len; i++) {
      bytes[i] = binary_string.charCodeAt(i);
    }
    return bytes.buffer;
  }

发布评论

评论列表(0)

  1. 暂无评论