MVC FileDownload as BLOB object using javascript
MVC FileDownload as BLOB object using javascript
Controller:
----------
public class BaseController : Controller
{
public async Task DownloadDocument(string id)
{
var tuple = default(Tuple);
try
{
var service = new xxxxxService();
//if (Regex.IsMatch(id, "^[a-zA-Z0-9-]+$"))//if (srdDocNum.All(char.IsLetterOrDigit))
if (id.Any(char.IsLetter))
tuple = await service.GetDownloadFileByDocNum(id); //SRD--Num
else
tuple = await service.DownloadDocumentAsync(id);
if (tuple?.Item1 != null)
{
var bytes = (tuple.Item1).ToArray();
return File(bytes, "application/octet-stream", tuple.Item2);
}
else
{
//return View("~/Views/Error/PageNotFound.cshtml");
return File(new byte[0], "application/octet-stream", "nofile");
//Response.StatusCode = 404;
}
}
catch (Exception ex)
{
LogHelper.Error($"Base/DownloadDocument: {ex.Message.ToString()}");
}
return new EmptyResult();
}
}
HTML:
----
< a class="product-link bg-grey-btn mb-3" data-docnum="SRD-xxx-xxx-12345" href="javascript:void(0);" onclick="fndownloadSafetyDataSheet(this); return false;">Data Sheet</a>
JavaScript:
---------
const fndownloadSRDDoc = async (e) => {
let docNum = e.dataset.docnum;// "SRD-xxx-xxx-0010";
let btnVal = $(e).html();
$(e).html('' + btnVal);
let tempUrl = window.location.href.toLowerCase().split("productsandpipeline");
let newUrl = tempUrl[0] + "base";
const srdDwld = new URL(newUrl + '/DownloadDocument?id=' + docNum);
const headers = new Headers();
//const headers = new Headers({ Authorization: 'Bearer ' + medInfoToken });
////headers.append("Authorization", "Bearer " + medInfoToken);
////headers.append("Content-Type", "application/octet-stream; charset=utf-8");
////headers.append("responseType", "blob");
try {
const srd = await fetch(srdDwld, { headers });
const response = await srd.blob();
let attr1 = srd.headers.get('content-disposition');
const filename = !attr1 ? [] : attr1.split(';').filter(x => x)
.find(n => n.includes('filename='))
.replace('filename=', '').replaceAll('\"', '').trim();
//var response2 = JSON.stringify(response),
var blob = new Blob([response], { type: "octet/stream" }),
url = window.URL.createObjectURL(blob);
const a = document.createElement('a');
a.href = url;
a.download = filename || 'nofile';
a.click();
window.URL.revokeObjectURL(url);
$(e).html(btnVal);
} catch (err) { console.log("fndownloadSRDDoc:", err); $(e).html(btnVal);}
};
//OR
const fndownloadSafetyDataSheet = async (e) => {
const docNum = e.dataset.docnum;
if (!docNum) {
console.error("Missing docnum attribute in the element.");
return;
}
const btnElement = $(e);
const btnVal = btnElement.html();
if (btnElement.html().indexOf("spinner") < 0) {
btnElement.html('' + btnVal);
btnElement.data('original-html', btnVal);
}
const currentURL = window.location.href.toLowerCase();
const newURL = currentURL.split("productsandpipeline")[0] + "base";
const downloadURL = new URL(newURL + '/downloaddocument?id=' + docNum);
const headers = new Headers();
//const headers = new Headers({ Authorization: 'Bearer ' + medInfoToken });
////headers.append("Authorization", "Bearer " + medInfoToken);
////headers.append("Content-Type", "application/octet-stream; charset=utf-8");
////headers.append("responseType", "blob");
downloadFile(downloadURL, headers, btnElement);
};
const downloadFile = async (url, headers, btnElement) => {
try {
const response = await fetch(url, { headers });
const filename = response.headers.get('content-disposition')
.split(';')
.map(item => item.trim().replaceAll('\"', ''))
.find(item => item.startsWith('filename='))
.split('=')[1];
if (!filename) {
console.warn("No filename found in the response headers.");
}
const blob = await response.blob();
const blobdata = new Blob([blob], { type: "octet/stream" });
const objectURL = window.URL.createObjectURL(blobdata);
const a = document.createElement('a');
a.href = objectURL;
a.download = filename || 'nofile';
a.style.display = 'none';
document.body.appendChild(a);
a.click();
window.URL.revokeObjectURL(objectURL);
if (btnElement) {
btnElement.html(btnElement.data('original-html'));
}
} catch (err) {
console.error("Download failed:", err);
if (btnElement) {
btnElement.html(btnElement.data('original-html'));
}
}
};
Comments