Angular Download File from server , C# Rest Api
Posted on Thursday, September 9, 2021
|
No Comments
HTML
<div class="input-group-append">
<button type="button" class="btn btn-primary"
(click)="downloadButtonClick('inputGroupFile03')">
<i class="fas fa-download"> </i>
Download</button>
</div>
Type Script
downloadButtonClick(fileName: string) {
let binaryData: any = [];
this.http.get(this.env.apiUrl + 'api/Supplier/get_doc_details_by_id2?id=' + this.model.SupID , { responseType: "blob" }).subscribe(data => {
binaryData.push(data);
let dataType = data.type;
let downloadLink = document.createElement('a');
downloadLink.href = window.URL.createObjectURL(new Blob(binaryData, { type: dataType }));
downloadLink.setAttribute('download', "File Name.ext");
document.body.appendChild(downloadLink);
downloadLink.click();
}, error => {
console.error(error)
this.alertService.error(error);
});
}
Web Api
[Authorize(Policy = nameof(Policy.Account))]
[HttpGet("get_doc_details_by_id2")]
public ActionResult GetDocDetailsById2(string id)
{
try
{
var data = _shopService.FindDocumentById(id);
if(data != null) {
[HttpGet("get_doc_details_by_id2")]
public ActionResult GetDocDetailsById2(string id)
{
try
{
var data = _shopService.FindDocumentById(id);
if(data != null) {
string fileType_ = "application/octet-stream";
if (data.fileName.ToLower().Contains("pdf"))
{
fileType_ = "application/pdf";
}
return File(data.fileByteArray, fileType_ , data.filename);
}
if (data.fileName.ToLower().Contains("pdf"))
{
fileType_ = "application/pdf";
}
return File(data.fileByteArray, fileType_ , data.filename);
}
return NotFound();
}
catch (Exception ex)
{
return StatusCode(500, ex.Message + ex.StackTrace);
}
}
}
catch (Exception ex)
{
return StatusCode(500, ex.Message + ex.StackTrace);
}
}