Skip to content

Instantly share code, notes, and snippets.

@relyky
Last active April 29, 2021 04:17
Show Gist options
  • Save relyky/a64bdfc57526ce5e0435bd2ad4069eca to your computer and use it in GitHub Desktop.
Save relyky/a64bdfc57526ce5e0435bd2ad4069eca to your computer and use it in GitHub Desktop.
jquery ajax download file, jQuery的ajax下載blob檔案
[HttpPost]
public FileResult DownloadFile(IndexArgs args)
{
var dataList = _biz.QueryFormData(args.formNo, args.spentAmount);
//## 轉成Excel
Byte[] excelFileContent;
_biz.ExporyExcel(dataList, out excelFileContent);
return File(excelFileContent, System.Net.Mime.MediaTypeNames.Application.Octet);
}
/*
* jQuery 3.5.1
* jquery-ajax-blob-arraybuffer.js
* file-saver 2.x
*/
@*
bundles.Add(new ScriptBundle("~/bundles/jquery").Include(
"~/Scripts/jquery-{version}.js",
"~/Scripts/jquery.unobtrusive-ajax.js",
"~/plugin/jquery-ajax-blob-arraybuffer.js",
"~/plugin/file-saver/FileSaver.min.js"));
*@
<p>
<button class="btn btn-default btn-sm"
onclick="downloadFile('@Url.Action("DownloadFile", queryArgs)', "下載檔名.xlsx")">
下載檔案
</button>
</p>
@Scripts.Render("~/bundles/jquery")
@section Scripts {
<script type="text/javascript">
function downloadFile(url, fileName) {
console.log('downloadFile', fileName, url);
$.ajax({
type: "POST",
url: url,
dataType: "blob", //<-- key code
success: function (data, status, xhr) {
var blob = new Blob([data]);
saveAs(blob, fileName);
},
error: function (xhr, status, err) {
alert("失敗!");
}
});
}
</script>
}
///
/// jQuery的ajax下載blob檔案 with FileSaver
///## 參考自:
/// ref → https://codertw.com/%E5%89%8D%E7%AB%AF%E9%96%8B%E7%99%BC/262905/
///
<script src="~/Scripts/jquery/3.2.1/jquery.js"></script>
<script src="~/Scripts/jquery-ajax-blob-arraybuffer.js"></script> //<-- key code
<script src="~/Scripts/FileSaver.min.js"></script>
<script type="text/javascript">
function ExportToExcel() {
$.ajax(
{
type: "POST",
url: '@Url.Action("ExportToExcel")',
dataType: "blob", //<-- key code
success: function (data, status, xhr) {
var blob = new Blob([data], { type: 'application/vnd.ms-excel' });
saveAs(blob, "excelFile.xlsx");
alert("成功。");
},
error: function (xhr, status, err) {
alert("失敗!");
}
}
)
}
</script>
/**
* Register ajax transports for blob send/recieve and array buffer send/receive via XMLHttpRequest Level 2
* within the comfortable framework of the jquery ajax request, with full support for promises.
*
* Notice the +* in the dataType string? The + indicates we want this transport to be prepended to the list
* of potential transports (so it gets first dibs if the request passes the conditions within to provide the
* ajax transport, preventing the standard transport from hogging the request), and the * indicates that
* potentially any request with any dataType might want to use the transports provided herein.
*
* Remember to specify 'processData:false' in the ajax options when attempting to send a blob or arraybuffer -
* otherwise jquery will try (and fail) to convert the blob or buffer into a query string.
*/
$.ajaxTransport("+*", function (options, originalOptions, jqXHR) {
// Test for the conditions that mean we can/want to send/receive blobs or arraybuffers - we need XMLHttpRequest
// level 2 (so feature-detect against window.FormData), feature detect against window.Blob or window.ArrayBuffer,
// and then check to see if the dataType is blob/arraybuffer or the data itself is a Blob/ArrayBuffer
if (window.FormData && ((options.dataType && (options.dataType == 'blob' || options.dataType == 'arraybuffer'))
|| (options.data && ((window.Blob && options.data instanceof Blob)
|| (window.ArrayBuffer && options.data instanceof ArrayBuffer)))
)) {
return {
/**
* Return a transport capable of sending and/or receiving blobs - in this case, we instantiate
* a new XMLHttpRequest and use it to actually perform the request, and funnel the result back
* into the jquery complete callback (such as the success function, done blocks, etc.)
*
* @param headers
* @param completeCallback
*/
send: function (headers, completeCallback) {
var xhr = new XMLHttpRequest(),
url = options.url || window.location.href,
type = options.type || 'GET',
dataType = options.dataType || 'text',
data = options.data || null,
async = options.async || true;
xhr.addEventListener('load', function () {
var res = {};
res[dataType] = xhr.response;
completeCallback(xhr.status, xhr.statusText, res, xhr.getAllResponseHeaders());
});
xhr.open(type, url, async);
xhr.responseType = dataType;
xhr.send(data);
},
abort: function () {
jqXHR.abort();
}
};
}
});
/// <summary>
/// 匯出Excel
/// </summary>
public ActionResult ExportToExcelAsync()
{
var dataList = LoadDataList(...);
try
{
//# 轉成Excel檔
Byte[] excelFileContent;
_biz.MakeDataListAsExcelFile(model, out excelFileContent);
string fileName = "執行-" + DateTime.Now.ToString("yyyy/MM/dd") + ".xlsx";
return File(excelFileContent, System.Net.Mime.MediaTypeNames.Application.Octet, fileName);
}
catch (Exception ex)
{
return Json(ex); // logical error
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment