Thinkhoop
Thinkhoop

Reputation: 619

"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?

Upvotes: 39

Views: 56944

Answers (2)

Thinkhoop
Thinkhoop

Reputation: 619

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

Upvotes: 0

Ahti Ahde
Ahti Ahde

Reputation: 1168

The first parameter should be sequence.

Thus, this will not work:

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

But this will:

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

Upvotes: 88

Related Questions