I'm returning a a PDF or XLSX file to the browser. I do this by setting the responseType of the ajax object that initiated the request to 'blob'. This seems to work as needed. I'm having problems figuring out a good way to pass an error string to the browser in cases where the file couldn't be created.
If I don't set any responseType on the ajax object I can read the response text as the meaninful error string I've set. This, though, means that I'm no longer able to properly read the response as a PDF or XLSX file in the cases where things proceeded properly. And, of course, I can't set the responseType of the ajax object after I've received the response.
Controller
public ActionResult GetFile() {
// process work, set stream and success bool
if (wasSuccessful) {
return File(stream, "application/pdf");
}
else {
return Content("a meaningful error for the UI");
}
}
cshtml
function getFile(e, extension) {
var xhr = new XMLHttpRequest();
xhr.open('POST', e.value, true);
xhr.responseType = 'blob';
xhr.setRequestHeader('Content-Type', "application/x-www-form-urlencoded");
xhr.onload = function (ee) {
if (this.status == 200) {
var a = document.createElement("a");
document.body.appendChild(a);
a.style = "display: none";
var blob = new Blob([this.response], { type: 'octet/stream' }), url = window.URL.createObjectURL(blob);
a.href = url;
a.download = "file." + extension;
a.click();
window.URL.revokeObjectURL(url);
}
};
xhr.send($("#form").serialize());
}
Can I have my ajax expect a blob but somehow read a simple string in certain error conditions?