Chrome error on downloading file via iframe

I'm submitting JSON data to a server. The server generates a PDF file and responds with the URL to that PDF file. I then make another request to the server to download the PDF file. To do the download, I create a hidden iframe and set the source the the PDF url. Note that I want the user's browser to stay on the same page and download in the background. More details about what I'm doing and the solution I went with can be found in this SO question.

Whenever I use this technique in Chrome, everything works fine. But looking at the chrome developer console, I see the error message Failed to load resource. Is there a way to do this differently so that I won't get these errors?

A very simple and working example of the problem in action can be seen on jsfiddle. Just click the Download PDF button and look at your Chrome console.

The code on that page looks like this:

$(document).ready( function() {
    var downloadFile = function(url){
        var iframe = $("iframe#download");
        if (!iframe.length) {
            iframe = $("<iframe id='download' style='display:none;'/>");
            $("body").append(iframe);
        }
        iframe.attr("src", url);
    };

    $("button").click(function() {    
        downloadFile("http://www.education.gov.yk.ca/pdf/pdf-test.pdf");
    });
});

Answers


Other respondents have suggested changing the content-type header, which should work just as well, but there's a specific response header for instructing the browser how to treat a file.

The following should force the pdf to be downloaded rather than displayed in the browser:

"Content-disposition: attachment; filename=[your file's name]"


Need Your Help

Should I ONLY have to worry about new and match them with deletes?

c++ memory-management memory-leaks

I have a C++ code in which I have multiple data types. Importantly, I have a class:

About UNIX Resources Network

Original, collect and organize Developers related documents, information and materials, contains jQuery, Html, CSS, MySQL, .NET, ASP.NET, SQL, objective-c, iPhone, Ruby on Rails, C, SQL Server, Ruby, Arrays, Regex, ASP.NET MVC, WPF, XML, Ajax, DataBase, and so on.