下载文件时“无法构造'Blob':提供的值无法转换为序列”

问题描述 投票:0回答:2

我正在尝试使用 AJAX/JQuery 下载并保存 PDF 文件(我知道......)。

这是我在服务器端的内容:

public HttpResponseMessage GetPdf() {
    var pdf = generatePdfByteArray(); // byte[]
    var result = Request.CreateResponse(HttpStatusCode.OK);
    result.Content = new ByteArrayContent(pdf);
    //result.Content.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment")
    //{
    //    FileName = "blah.pdf"
    //};
    // Tried with and without content disposition… Shouldn't matter, I think?
    result.Content.Headers.ContentType = new MediaTypeHeaderValue("application/pdf");
    return result;
}

这是客户端:

let ajaxOptions = {
    url: "/url",
    type: "GET",
    accepts: "application/pdf",
    success: (data) => {
        let blob = new Blob(data, {
            type: "application/pdf",
        }); // <-- this fails

        // stuff...
    },
};
$.ajax(ajaxOptions);

你知道这有什么问题吗?

jquery ajax asp.net-web-api2
2个回答
86
投票

第一个参数应该是序列。

因此,这是行不通的:

let blob = new Blob(data, {
    type: "application/pdf"
});

但这会:

let blob = new Blob([data], {
    type: "application/pdf"
});


0
投票

这就是我最终的结果:

public HttpResponseMessage GetPdf()
{
    var pdf = generatePdfByteArray();

    var result = Request.CreateResponse(HttpStatusCode.OK);
    var dataStream = new MemoryStream(pdf);
    result.Content = new StreamContent(dataStream);
    result.Content.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment")
    {
        FileName = "file.pdf"
    };
    result.Content.Headers.ContentType = new MediaTypeHeaderValue("application/pdf");

    return result;
}
© www.soinside.com 2019 - 2024. All rights reserved.