簡體   English   中英

C# 字節數組到 Javascript Blob 以創建和自動下載 PDF 文件

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

我在 C# 中有 web api,它返回 PDF 文件的字節數組。 這是 C# 代碼

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

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

這就是我使用 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)
        });
}

上面確實創建並打開了一個 pdf 文件,但它已損壞。

console.log('Success:', result); ,控制台中的輸出如下所示:

Success: JVBERi0xLjUNCiW1tbW1DQoxIDAgb2JqDQo8PC9UeXBlL0NhdGFsb2cvUGFnZXMgMiAwIFIvTGFuZyhlbi1NWSkgL1N0cnVjdFRyZWVSb290IDI3OCAwIFIvTWFya0luZm88PC9NYXJrZWQgdHJ1ZT4+Pj4NCmVuZG9iag0KMiAwIG9iag0KPDwvVHlwZS9QYWdlcy9Db3VudCAzNS9LaWRzWyAzIDAgUiAxNyAwIFIgMjggMCBSIDMxIDAgUiAzOCAwIFIgNDAgMCBSIDQ0IDAgUiA0NSAwIFIgNDYgMCBSIDQ3IDAgUiA0OCAwIFIgNDkgMCBSIDUxIDAgUiA1MiAwIFIgNTMgMCBSIDU0IDAgUiA1NSAwIFIgNTYgMCBSIDU3IDAgUiA1OCAwIFIgNTkgMCBSIDYwIDAgUiA2MSAwIFIgNjIgMCBSIDYzIDAgUiA2NCAwIFIgNjUgMCBSIDY2IDAgUiA2NyAwIFIgNjggMCBSIDY5IDAgUiA3MCAwIFIgNzEgMCBSIDI2NiAwIFIgMjczIDAgUl0gPj4NCmVuZG9iag0KMyAwIG9iag0KPDwvVHlwZS9QYWdlL1BhcmVud

由於實際輸出太長,我這里截斷了。

在谷歌搜索更多之后,我還嘗試了以下代碼,該代碼在創建 blob 之前將字節數組轉換為 arrayBuffer。 它確實創建並下載了 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')

對於FetchFiles方法,基本上它讀取 PDF 文件並將其轉換為字節數組。

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

您的代碼將字節數組返回給 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