【问题标题】:"Failed to construct 'Blob': The provided value cannot be converted to a sequence" when downloading file下载文件时“构造‘Blob’失败:提供的值无法转换为序列”
【发布时间】:2019-08-03 11:35:36
【问题描述】:

我正在尝试使用 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);

你知道这有什么问题吗?

【问题讨论】:

  • 为什么你想让blob变得简单只需点击调用API的锚点或按钮,其余的将由浏览器完成
  • 因为我想拦截呼叫并在服务器出现问题时显示消息

标签: jquery ajax asp.net-web-api2


【解决方案1】:

这就是我最终的结果:

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;
}

【讨论】:

    【解决方案2】:

    第一个参数应该是序列。

    因此,这将不起作用:

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

    但这会:

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

    【讨论】:

      猜你喜欢
      • 2020-06-13
      • 1970-01-01
      • 1970-01-01
      • 2021-07-02
      • 1970-01-01
      • 2020-09-22
      • 2015-08-14
      • 1970-01-01
      • 2019-07-05
      相关资源
      最近更新 更多