I have a .NET route that I want to hit when I want to get a document, now It can either return Json or a full fledged file whose name and extension is determined through some logic.
Here some sample code:
public async Task<IActionResult> DownloadAndServeFile(List<string> num_lst, bool view)
{
cancellationToken.ThrowIfCancellationRequested();
HttpContext.RequestAborted.ThrowIfCancellationRequested();
if (browserSupportedExtensions.Contains(Path.GetExtension(fileName).ToLower()) && view == "true")
{
string fileUrlToServe = Url.Content($"~/DownloadedFiles/{fileName}");
return Json(new { success = true, url = fileUrlToServe, openInBrowser = true });
}
else
{
byte[] fileBytes = await System.IO.File.ReadAllBytesAsync(savePath);
// adding bytes to memory stream
return File(fileBytes, "application/octet-stream", fileName);
}
}
And here's how I hit this endpoint from Javascript:
```js
$.ajax({
type: "POST",
url: '/Home/DownloadAndServeFile',
data: { id: some_num },
success: function (response, status, xhr) {
// Check if the content type is JSON
var contentType = xhr.getResponseHeader('Content-Type');
if (contentType.includes('application/json')) {
// The server returned a JSON response
if (response.success) {
window.location.href = response.url;
const link = document.createElement('a');
link.href = response.url;
link.download = '';
document.body.appendChild(link);
link.click();
document.body.removeChild(link);
}
else {
showToast(response.message, "error");
}
} else {
// The server returned a file directly (binary data)
console.log(xhr.getResponseHeader('Content-Disposition'));
var fileName = xhr.getResponseHeader('Content-Disposition').split(';')[1].split('filename=')[1];
var blob = new Blob([response], { type: xhr.getResponseHeader('Content-Type') });
var link = document.createElement('a');
link.href = window.URL.createObjectURL(blob);
link.download = fileName;
link.click();
}
},
error: function (xhr, status, error) {
}
});
The problem is: everything works as I want, but now suppose when the popup comes up the user presses no, instead of yes to download then the .NET connection times out.
My guess is that the server has started transmitting the file, but cannot get the user to acknowledge and it times itself out.
How do I fix this?
3