Skip to content

Instantly share code, notes, and snippets.

@MarioBinder
Last active August 22, 2017 09:27
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save MarioBinder/2e14386eef0f2f637b5c8319e44c42b8 to your computer and use it in GitHub Desktop.
Save MarioBinder/2e14386eef0f2f637b5c8319e44c42b8 to your computer and use it in GitHub Desktop.
ForceDownload Ajax, ASP.NET MVC
public ActionResult Export(ViewModel model)
{
var fileData = _repo.GetFile(model...);
var serializer = new JavaScriptSerializer { MaxJsonLength = Int32.MaxValue, RecursionLimit = 100 };
var dataJson = new DownloadAjaxResult(true)
{
File = fileData,
Filename = model.Filename
};
return new ContentResult()
{
Content = serializer.Serialize(dataJson),
ContentType = "application/json",
};
}
forceDownload: function (response) {
var success = false;
var arr = response.Data.File;
var byteArray = new Uint8Array(arr);
try {
var blob = new Blob([byteArray], { type: 'application/octet-stream' });
if (navigator.msSaveBlob) {
navigator.msSaveBlob(blob, response.Data.Filename);
} else {
var saveBlob = navigator.webkitSaveBlob || navigator.mozSaveBlob || navigator.saveBlob;
if (saveBlob === undefined) throw "Not supported";
saveBlob(blob, response.Data.Filename);
}
success = true;
} catch (ex) { }
if (!success) {
var urlCreator = window.URL || window.webkitURL || window.mozURL || window.msURL;
if (urlCreator) {
var link = document.createElement('a');
if ('download' in link) {
try {
var blob1 = new Blob([byteArray], { type: 'application/octet-stream' });
var url1 = urlCreator.createObjectURL(blob1);
link.setAttribute('href', url1);
// Set the download attribute (Supported in Chrome 14+ / Firefox 20+)
link.setAttribute("download", response.Data.Filename);
// Simulate clicking the download link
var event = document.createEvent('MouseEvents');
event.initMouseEvent('click', true, true, window, 1, 0, 0, 0, 0, false, false, false, false, 0, null);
link.dispatchEvent(event);
success = true;
} catch (ex) { }
}
if (!success) {
// Fallback to window.location method
try {
var blob2 = new Blob([byteArray], { type: 'application/octet-stream' });
var url2 = urlCreator.createObjectURL(blob2);
window.location = url2;
success = true;
} catch (ex) { }
}
}
}
}
[Serializable]
public class DownloadAjaxResult
{
public bool Success { get; set; }
public string Message { get; set; }
public string Filename { get; set; }
public byte[] File { get; set; }
public DownloadAjaxResult(bool success)
{
Success = success;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment