简体   繁体   English

C# 字节数组到 Javascript Blob 以创建和自动下载 PDF 文件

[英]C# Bytes array to Javascript Blob to create and auto download PDF file

I have web api in C# which returns bytes array of PDF file.我在 C# 中有 web api,它返回 PDF 文件的字节数组。 Here is the C# code这是 C# 代码

    [HttpGet]
    [Route("Download")]
    public async Task<ActionResult<byte[]>> DownloadFiles(int fileDocumentId)
    {

            var file = await _fileService.FetchFiles(fileDocumentId);
            return file.ArchiveData;
    }

This is how I call the web api using Javascript fetch.这就是我使用 Javascript fetch 调用 web api 的方式。

function download(id) {
    fetch(`https://localhost:xxx/api/file/download?fileDocumentId=11`)
        .then(response => {
            debugger

            return response.json()
        })
        .then(result => {
            debugger
            console.log('Success:', result);       

            var file = new Blob([result], { type: 'application/pdf' });
            var fileURL = URL.createObjectURL(file);
            window.open(fileURL);         
        })

        .catch(function (error) {
            console.log('Request failed', error)
        });
}

The above did create and open a pdf file but it is corrupted.上面确实创建并打开了一个 pdf 文件,但它已损坏。

In console.log('Success:', result);console.log('Success:', result); , the output in the console is something like below: ,控制台中的输出如下所示:

Success: JVBERi0xLjUNCiW1tbW1DQoxIDAgb2JqDQo8PC9UeXBlL0NhdGFsb2cvUGFnZXMgMiAwIFIvTGFuZyhlbi1NWSkgL1N0cnVjdFRyZWVSb290IDI3OCAwIFIvTWFya0luZm88PC9NYXJrZWQgdHJ1ZT4+Pj4NCmVuZG9iag0KMiAwIG9iag0KPDwvVHlwZS9QYWdlcy9Db3VudCAzNS9LaWRzWyAzIDAgUiAxNyAwIFIgMjggMCBSIDMxIDAgUiAzOCAwIFIgNDAgMCBSIDQ0IDAgUiA0NSAwIFIgNDYgMCBSIDQ3IDAgUiA0OCAwIFIgNDkgMCBSIDUxIDAgUiA1MiAwIFIgNTMgMCBSIDU0IDAgUiA1NSAwIFIgNTYgMCBSIDU3IDAgUiA1OCAwIFIgNTkgMCBSIDYwIDAgUiA2MSAwIFIgNjIgMCBSIDYzIDAgUiA2NCAwIFIgNjUgMCBSIDY2IDAgUiA2NyAwIFIgNjggMCBSIDY5IDAgUiA3MCAwIFIgNzEgMCBSIDI2NiAwIFIgMjczIDAgUl0gPj4NCmVuZG9iag0KMyAwIG9iag0KPDwvVHlwZS9QYWdlL1BhcmVud

Since the actual output is too long, I have truncated it here.由于实际输出太长,我这里截断了。

After googling more, I also tried the below code which convert the bytes array into arrayBuffer before create the blob.在谷歌搜索更多之后,我还尝试了以下代码,该代码在创建 blob 之前将字节数组转换为 arrayBuffer。 It did create and download the PDF but when I open the PDF, that PDF is also corrupted.它确实创建并下载了 PDF,但是当我打开 PDF 时,该 PDF 也已损坏。

function downloadpdf(pdfUrl) {
    debugger
    fetch(pdfUrl).then(resp => resp.arrayBuffer()).then(resp => {
        const file = new Blob([resp], { type: 'application/pdf' });

        const fileURL = URL.createObjectURL(file);
        const link = document.createElement('a');
        link.href = fileURL;
        link.download = "FileName" + new Date() + ".pdf";
        link.click();
    });
}

downloadpdf('https://localhost:xxx/api/file/download?fileDocumentId=11')

For FetchFiles method, basically it read the PDF file and convert it into bytes array.对于FetchFiles方法,基本上它读取 PDF 文件并将其转换为字节数组。

byte[] fileBytes = await File.ReadAllBytesAsync(file);

Your code returning byte array to JavaScript and you don't need to do that, just return it as FileContentResult which will write a binary file to the response and the browser will download it as a file even if you call the API directly in the browser.您的代码将字节数组返回给 JavaScript,您不需要这样做,只需将其作为FileContentResult返回,它将向响应写入一个二进制文件,即使您直接在浏览器中调用 API,浏览器也会将其下载为文件.

[HttpGet]
[Route("Download")]
public async Task<ActionResult> DownloadFiles(int fileDocumentId)
{
    string filePath = fileDocumentId=11;

    var file = await _fileService.FetchFiles(fileDocumentId);
    string fileName = "FileName" + DateTime.Now.ToString() + ".pdf";

    return File(file.ArchiveData, "application/force-download", fileName);
}

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

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