简体   繁体   中英

How to start browser file download from javascript, only if a web service returned correct content

I need to build javascript that triggers on a click to <a> element and invokes a GET call to a web service (I am coding the service also). The service should return a file and only if no error occurred offer it for user to download from browser, otherwise leave him on the page where some other component will render the error.

The way I know to do it is to set "href" attribute of the <a> element to the URL of the service.

Due to the specifics of the app I am building this for, I am not returning an error but html with "errorOccurred" content (it might be file with the same content too).

So, my question is: how to start file download from a javascript method (I am using jQuery.ajax) I have attached to onclick attribute of <a> element only if the retrieved file content is ok?

A solution found here

I am copy pasting the code given there:

var textToSave = 'this is a test';

var hiddenElement = document.createElement('a');

hiddenElement.href = 'data:attachment/text,' + encodeURI(textToSave);
hiddenElement.target = '_blank';
hiddenElement.download = 'myFile.txt';
hiddenElement.click();

Try searching for " errorOccurred " text in the HTML document.

Use the "indexOf" method to see if the string exists in the returned HTML.

if(returnedText.indexOf('errorOccurred') > -1) {...code to download file}

Ok. You have control over the service so instead of returning html with a textual error message when the service fails, return a 400 type error.

Then in your jQuery.ajax do something like this:

jQuery.ajax {
    dataType:....
    url:...
    data:...
    success:...
    error: function(){
        alert('Your error message');
    }
}

If you are using PHP on the server side, you can use the following to generate a 400 type error:

header('HTTP/1.1 404');

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM