jqueryajaxasp.net-web-api2

"Failed to construct 'Blob': The provided value cannot be converted to a sequence" when downloading file


I'm trying to download and save a PDF file using AJAX/JQuery (I know…).

This is what I have on the server side:

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

This is the client side:

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

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

Any ideas what's wrong with this?


Solution

  • This is what I ended up with:

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