Download file on button click - c#

I have a application where a button click needs to download a text log file. I wrote the backend API, but am not able to connect it from the frontend button click. Working on Angular 2 and C#. What changes do I need to make to component.ts file?
Button code:
<div class="col-lg-4"> <button type="button" class="btn btn-info pull-right" [hidden]="!dbtn" (click)="GetMigrationLog()" id="downloadLog" translate>Download Log</button> </div>
Here is my backend api code:
[Route("GetMigrationLog")]
public IHttpActionResult GetMigrationLog()
{
try
{
IDBMigrationDataBo data = _serviceLocator.Resolve<IDBMigrationDataBo>();
var result = data.GetMigrationLog();
string logFileName = string.Format("Migration_{0}.txt", DateTime.Now.ToString("dd-MM-yyyy"));
return StreamResponse(result, logFileName);
}
catch (Exception ex)
{
logger.Error(ex.Message);
return this.HandleError(ex);
}
}

I've done somthing similar .. it's a little bit difficult .. i share my experience and my code with you .. hope it helps you!!
in your html
Download Log
in your ts:
saveFile(id: string, name: string) {
this._orderService.DownloadRicetta(id, name).then((result) => {
this._toaster.pop('success', 'Download', 'Ricetta Scaricata con Successo');
}).catch((err) => {
this._toaster.pop('error', 'Download', 'Errore nel Download della Ricetta!')
console.log(err);
});
}
in your service file:
first of all import a package (installed with npm i --save file-saver #types/file-saver)
import * as FileSaver from 'file-saver';
then write your method like this:
public async DownloadRicetta(id: string, name: string): Promise<Blob> {
return new Promise<Blob>((resolve, reject) => {
const headers = new HttpHeaders();
headers.append('Accept', 'text/plain'); //just check the type you need
this._http.get(environment.API_URL + `Order/${id}/Download/Ricetta`, { headers: headers, responseType: "blob", observe: 'response' })
.subscribe(response => {
try {
let blob = this.saveToFileSystem(response, name);
resolve(blob);
} catch (error) {
reject(error);
}
});
});
}
private saveToFileSystem(response, name: string): Blob {
const contentDispositionHeader: string = response.headers.get('Content-Disposition');
//for get original filename
const parts: string[] = contentDispositionHeader.split(';');
const filename = parts[1].trim().split('=')[1].trim();
//get extension of the file
const parts2: string[] = contentDispositionHeader.split('.');
let ext = parts2[1];
ext = ext.replace('"', '')
//set mimetype
let mimeType = Utils.extToMimeType(ext);
const blob = new Blob([response.body], { type: mimeType });
FileSaver.saveAs(blob, name + '_ricetta.' + ext);
return blob;
}
file UTILS.ts:
export default class Utils {
static extToMimeType(ext: string) {
switch (ext) {
case "pdf":
return "application/pdf";
case "jpg":
return "image/jpg";
case "png":
return "image/png";
case "txt":
return "text/plain";
default:
return "";
}
}
}
AND ALSO BACK END (ASP.NET WEBAPI 2 ):
[HttpGet]
[Route("api/Order/{id}/Download/Ricetta")]
public async Task<HttpResponseMessage> GetBookForHRM([FromUri] string id)
{
try
{
if (string.IsNullOrEmpty(id)) return new HttpResponseMessage { StatusCode = HttpStatusCode.BadRequest };
var order = await _orderService.FindAsync(xx => xx.Id == id);
if (order == null) return new HttpResponseMessage { StatusCode = HttpStatusCode.BadRequest };
if (string.IsNullOrEmpty(order.RicettaUrl)) return new HttpResponseMessage { StatusCode = HttpStatusCode.BadRequest };
var user = await _aspNetService.FindAsync(xx => xx.Id == order.IdUser);
if (user == null) return new HttpResponseMessage { StatusCode = HttpStatusCode.BadRequest };
var fileWithPath = $#"{user.GetUserRicettaDirectory()}/{order.RicettaUrl}";
//converting Pdf file into bytes array
var dataBytes = File.ReadAllBytes(fileWithPath);
//adding bytes to memory stream
var dataStream = new MemoryStream(dataBytes);
HttpResponseMessage httpResponseMessage = Request.CreateResponse(HttpStatusCode.OK);
httpResponseMessage.Content = new StreamContent(dataStream);
httpResponseMessage.Content.Headers.Add("Access-Control-Expose-Headers", "Content-Disposition");
httpResponseMessage.Content.Headers.ContentDisposition = new System.Net.Http.Headers.ContentDispositionHeaderValue("attachment")
{
FileName = order.RicettaUrl.Trim()
};
httpResponseMessage.Content.Headers.ContentType = new System.Net.Http.Headers.MediaTypeHeaderValue("application/octet-stream");
return httpResponseMessage;
}
catch (Exception ex)
{
_logger.LogException(ex);
throw;
}
}

Related

List<IFormFile> Files always 0 Files count in AspNetCore 3.1 Web Api

I'm building a REST API application where I want to give an option to users they can upload single or multiple files, I checked with uploading files from Postman but in my controller, I always get zero files, Please help me to know what wrong I'm doing
Postman Image
Below is my code.
public async Task<IActionResult> UploadInvoice([FromForm(Name = "Files")] List <IFormFile> uploadFiles) {
try {
long size = uploadFiles.Sum(f => f.Length);
if (uploadFiles == null || uploadFiles.Count <= 0) {
Response.StatusCode = (int) HttpStatusCode.BadRequest;
return Content(JsonConvert.SerializeObject(new {
message = "No files found."
}), "application/json");
}
var filesToUpload = new List < FileUploadModel > ();
foreach(var file in uploadFiles) {
var fileGuid = Guid.NewGuid().ToString().Replace("-", "");
var path = Path.Combine(Directory.GetCurrentDirectory(), # "wwwroot\docs", $ "{fileGuid}{Path.GetExtension(file.FileName)}");
using(var fileStream = new FileStream(path, FileMode.Create)) {
await file.CopyToAsync(fileStream);
await fileStream.FlushAsync();
}
}
return Content(JsonConvert.SerializeObject(new {
message = ""
}), "application/json");
} catch (Exception ex) {
Response.StatusCode = (int) HttpStatusCode.InternalServerError;
return Content(JsonConvert.SerializeObject(new {
message = ex.Message
}), "application/json");
}
}

Problem with C# Web API export excel file that can not open the file because file format or file extension is not valid

I'm trying to generate excel file from my database and download the file from my website but when I open the excel file the error "can not open the file because file format or file extension is not valid." has occurred.
So, This is my code for doing this.
Here is my script:
$(document).ready(function () {
$("#btnExportExcel").click(function (e) {
e.preventDefault();
const deferred = $.Deferred();
var paymentType = $("#transactionTypeDropdown").val();
var paymentStatus = $("#paymentStatusDropdown").val();
var merchantName = $("#merchantNameDropdown").val();
var dateTime = $("#reservation").val().split(" ");
var refNo = $("#refNoInput").val();
var terminalId = $("#terminalID").val();
$.ajax({
type: "POST",
crossOrigin: true,
url: "/api/Transaction/ExportExcel",
headers: {
Accept: "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
},
data: {
"Date_1": dateTime[0],
"Date_2": dateTime[2],
"PaymentType": paymentType,
"Status": paymentStatus,
"Outtrade": refNo,
"Merchant": merchantName,
"TerminalID": terminalId
},
success: function (result) {
if (dateTime[0] == dateTime[2]) {
filename = "Transaction_Detail_" + dateTime[0].replace(/\//g, '-') + ".xlsx";
}
else {
filename = "Transaction_Detail_" + dateTime[0].replace(/\//g, '-') + " - "
+ dateTime[2].replace(/\//g, '-') + ".xlsx";
}
var uri = 'data:application/vnd.openxmlformats-officedocument.spreadsheetml.sheet,' + result;
var link = document.createElement("a");
link.href = uri;
link.style = "visibility:hidden";
link.download = filename;
document.body.appendChild(link);
link.click();
document.body.removeChild(link);
},
error: function (jqXHR, exception) {
getErrorMessage(jqXHR, exception);
}
});
return deferred.promise();
});
});
Here is my C# API:
public class TransactionController : ApiController
{
[AllowAnonymous]
[HttpPost]
[Route("api/Transaction/ExportExcel")]
public HttpResponseMessage ExportExcel(TransactionSearchReq req)
{
TransactionMgr transaction = new TransactionMgr();
List<TransactionRecordRes> transactionList = new List<TransactionRecordRes>();
HttpResponseMessage response = Request.CreateResponse(HttpStatusCode.OK);
MediaTypeHeaderValue mediaType = MediaTypeHeaderValue.Parse("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
byte[] fileContents;
string fileName;
try
{
// Get transaction records
transactionList = transaction.GetSearchTransactionRecord(req);
if (transactionList.Count() > 0)
{
ExcelPackage.LicenseContext = LicenseContext.NonCommercial;
using (var package = new ExcelPackage())
{
var worksheet = package.Workbook.Worksheets.Add("Sheet1");
// I put data to worksheet here.
fileContents = package.GetAsByteArray();
}
if (fileContents == null || fileContents.Length == 0)
{
response = Request.CreateResponse(HttpStatusCode.InternalServerError);
response.Content = new StringContent("Export file error.", Encoding.Unicode);
return response;
}
else
{
if (string.Compare(req.Date_1, req.Date_2) == 0)
{
fileName = string.Format("Transaction_Detail_{0}.xlsx", req.Date_1.Replace('/', '-'));
}
else
{
fileName = string.Format("Transaction_Detail_{0} - {1}.xlsx", req.Date_1.Replace('/', '-'), req.Date_2.Replace('/', '-'));
}
MemoryStream memoryStream = new MemoryStream(fileContents);
response.Content = new StreamContent(memoryStream);
response.Content.Headers.ContentType = mediaType;
response.Content.Headers.ContentDisposition =
new ContentDispositionHeaderValue("attachment") { FileName = fileName };
return response;
}
}
else
{
response = Request.CreateResponse(HttpStatusCode.InternalServerError);
response.Content = new StringContent("Export file error.", Encoding.Unicode);
return response;
}
}
catch (Exception ex)
{
response = Request.CreateResponse(HttpStatusCode.InternalServerError);
response.Content = new StringContent("Export file error.", Encoding.Unicode);
return response;
}
}
}
Where I'm going wrong ?

Send file from angular to create new and download from .net

I've been trying to download .xml file, but sadly unsuccesfully.
From angular side I am sending *.xml file. In .NET side I take it to process and create a new *.xml file. And I need to download that new file, however I can't really find out how to workaround it.
this is my file-component.ts:
OnSubmit(value, File) {
const params1: FormData = new FormData();
params1.append('File', this.fileToUpload, this.fileToUpload.name);
params1.append('ProcessingMode', value.processingMode);
params1.append('StartDate', value.startDate.formatted);
const params = {
'File': this.fileToUpload,
'ProcessingMode': value.processingMode,
'StartDate': value.startDate.formatted
};
this.mapsConfigurationService.postFile(value, this.fileToUpload, value.startDate.formatted)
.subscribe((res: any) => {
this.downloadFile(res, 'xml'); debugger;
this.xmlProcessing = false;
},
(err) => {
if (err.status === 401) {
// this.router.navigate(['unauthorized']);
} else {
this.xmlProcessing = false;
}
});
downloadFile(data, type) {
const fileName = 'test';
var contentType;
if (type === 'xml') {
contentType = 'text/xml';
}
var blob = new Blob([data._body], { type: contentType });
const dwldLink = document.createElement('a');
const url = URL.createObjectURL(blob);
const isSafariBrowser = navigator.userAgent.indexOf('Safari') !== -1 && navigator.userAgent.indexOf('Chrome') === -1;
if (isSafariBrowser) {
dwldLink.setAttribute('target', '_blank');
}
const fullFileName = fileName + '.' + type;
dwldLink.setAttribute('href', url);
dwldLink.setAttribute('download', fullFileName);
dwldLink.style.visibility = 'hidden';
document.body.appendChild(dwldLink);
dwldLink.click();
document.body.removeChild(dwldLink);}
this is service.ts
postFile(value: any, fileToUpload: File, startDate) {
const formData: FormData = new FormData();
formData.append('File', fileToUpload, fileToUpload.name);
formData.append('ProcessingMode', value.processingMode);
formData.append('StartDate', '2015-05-23');
return this.http
.post(this.Url, formData);
}
and this is backend side:
[HttpPost, DisableRequestSizeLimit]
public ActionResult UploadFile()
{
try
{
var xml = Request.Form.Files["File"].ToString();
var httpRequest = HttpContext.Request.Form;
var postedFile = httpRequest.Files["File"];
string outputFile = Request.Form["info"].ToString();
var startDate = Request.Form["StartDate"];
var file = httpRequest.Files[0];
string fullPath = "";
string folderName = "Upload";
string antFile = #"C:\ant.bat";
string build = #"C:\build.xml";
string rootPath = #"C:\Users";
string newPath = Path.Combine(rootPath, folderName);
if (!Directory.Exists(newPath))
{
Directory.CreateDirectory(newPath);
}
if (file.Length > 0)
{
string fileName = ContentDispositionHeaderValue.Parse(file.ContentDisposition).FileName.Trim('"');
fullPath = Path.Combine(newPath, fileName);
using (var stream = new FileStream(fullPath, FileMode.Create))
{
file.CopyTo(stream);
}
}
return PhysicalFile(#"C:\Book1.xml", "application/xml", "Book1.xml");
}
catch (System.Exception ex)
{
return StatusCode(500);
}
}
I get error 500 and I do understand that the problem is with RequestHeaders but I can't figure out the way to solve it and in which side
for downloading for downloading any file... I am use this code in backend
and make and request the code from angular by normal http request
var myFile :: your file
if (System.IO.File.Exists (myFile.Path)) {// to know if the file is Exist or not
//Process File Here ...
} else {
return Json ("NotFound");
}
string contentType = "application/xml";
HttpContext.Response.ContentType = contentType;
var result = new FileContentResult (System.IO.File.ReadAllBytes (myFile.Path), contentType) {
FileDownloadName = $"{myFile.Title }" // + myFile.Extension
};
// System.IO.File.Delete (myFile.Path); //if you want to delete the file after download
return result;

How to get Facebook profile Picture C# .Net

I need to get the user´s facebook profile picture and input it in a crop structure. I´m using Asp.NET MVC, jcrop and the facebook SDK. Untill now i can input files from my computer. I also have a function that access the facebook of the user and returns a session with the user Id, and a GetPhoto function that should return the profile picture. Can someone help me?
I use this code to input the files from the computer:
[ValidateAntiForgeryToken]
public ActionResult _Upload(IEnumerable<HttpPostedFileBase> files)
{
if (files == null || !files.Any()) return Json(new { success = false, errorMessage = "No file uploaded." });
var file = files.FirstOrDefault(); // get ONE only
if (file == null || !IsImage(file)) return Json(new { success = false, errorMessage = "File is of wrong format." });
if (file.ContentLength <= 0) return Json(new { success = false, errorMessage = "File cannot be zero length." });
var webPath = GetTempSavedFilePath(file);
//mistertommat - 18 Nov '15 - replacing '\' to '//' results in incorrect image url on firefox and IE,
// therefore replacing '\\' to '/' so that a proper web url is returned.
return Json(new { success = true, fileName = webPath.Replace("\\", "/") }); // success
}
i tried doing this but the GetPhoto() is returning a null element.
public ActionResult RetornoFb()
{
var _fb = new FacebookClient();
FacebookOAuthResult oauthResult;
if (!_fb.TryParseOAuthCallbackUrl(Request.Url, out oauthResult))
{
// Error
}
if (oauthResult.IsSuccess)
{
dynamic parameters = new ExpandoObject();
parameters.client_id = id;
parameters.redirect_uri = "http://localhost:4323/Avatar/RetornoFb/";
parameters.client_secret = secretkey;
parameters.code = oauthResult.Code;
dynamic result = _fb.Get("/oauth/access_token", parameters);
var accessToken = result.access_token;
Session.Add("FbUserToken", accessToken);
}
else
{
}
//return RedirectToAction("Upload");
HttpPostedFileBase objFile = (HttpPostedFileBase)new MemoryPostedFile(GetPhoto());
var webPath = GetTempSavedFilePath(objFile);
return Json(new { success = true, fileName = webPath.Replace("\\", "/") }); // success
}
public byte[] GetPhoto()
{
try
{
string url = "https://graph.facebook.com/" + GetProfileId() + "?fields=picture.width(480).height(480)";
WebClient webClient = new WebClient();
string response = webClient.DownloadString(url);
dynamic json = JObject.Parse(response);
string urlPicture = json.picture.data.url;
return webClient.DownloadData(urlPicture);
}
catch (Exception)
{
return null;
}
}
Resolved changing my GetPhoto Function. I was having permission issues.
private byte[] GetPhoto()
{
try
{
var _fb = new FacebookClient(Session["FbuserToken"].ToString());
dynamic resultMe = _fb.Get(GetProfileId()+"?fields=picture.width(480).height(480)");
WebClient webClient = new WebClient();
string urlPicture = resultMe.picture.data.url;
return webClient.DownloadData(urlPicture);
}
catch (Exception)
{
return null;
}
}

Pass the value to database in asp.net web api

Am trying to save the images to the database using the asp.net webapi. In this controller am saving the image into my /Content/Banner/ Folder.
[HttpPost]
[Route("PostBanner")]
[AllowAnonymous]
public HttpResponseMessage PostBannerImage()
{
Dictionary<string, object> dict = new Dictionary<string, object>();
try
{
var httpRequest = HttpContext.Current.Request;
foreach (string file in httpRequest.Files)
{
HttpResponseMessage response = Request.CreateResponse(HttpStatusCode.Created);
var postedFile = httpRequest.Files[file];
if (postedFile != null && postedFile.ContentLength > 0)
{
int MaxContentLength = 1024 * 1024 * 1; //Size = 1 MB
IList<string> AllowedFileExtensions = new List<string> { ".jpg", ".gif", ".png" };
var ext = postedFile.FileName.Substring(postedFile.FileName.LastIndexOf('.'));
var extension = ext.ToLower();
if (!AllowedFileExtensions.Contains(extension))
{
var message = string.Format("Please Upload image of type .jpg,.gif,.png.");
dict.Add("error", message);
return Request.CreateResponse(HttpStatusCode.BadRequest, dict);
}
else if (postedFile.ContentLength > MaxContentLength)
{
var message = string.Format("Please Upload a file upto 1 mb.");
dict.Add("error", message);
return Request.CreateResponse(HttpStatusCode.BadRequest, dict);
}
else
{
var filePath = HttpContext.Current.Server.MapPath("~/Content/Banner/" + postedFile.FileName + extension);
postedFile.SaveAs(filePath);
}
}
var message1 = string.Format("Image Updated Successfully.");
return Request.CreateErrorResponse(HttpStatusCode.Created, message1); ;
}
var res = string.Format("Please Upload a image.");
dict.Add("error", res);
return Request.CreateResponse(HttpStatusCode.NotFound, dict);
}
catch (Exception ex)
{
var res = string.Format("some Message");
dict.Add("error", res);
return Request.CreateResponse(HttpStatusCode.NotFound, dict);
}
}
Now what i need to send this filePath to database. I know i just need to pass this file path to the following service controller. But i dont know how to pass it. could anyone help me to solve this problem.
This Is my services.cs
public async Task<int?> Addbanner(DisplayBannersDto dto)
{
try
{
var d = _dbContext.Banners
.FirstOrDefault();
d.Banner_Description = dto.Description;
d.Banner_Location = dto.Location;
//mark entry as modifed
_dbContext.Entry(d).State = EntityState.Modified;
await _dbContext.SaveChangesAsync();
return d.Banner_Id;
}
catch (Exception ex)
{
throw ex;
}
}
This is my controller
[HttpPost]
[Route("AddBanner")]
public async Task<IHttpActionResult> AddBanner(DisplayBannersDto dto)
{
if (!ModelState.IsValid)
return BadRequest(ModelState);
int? result = await _service.Addbanner(dto);
return Ok();
}
Change your else condition like below:
else
{
var filePath = HttpContext.Current.Server.MapPath("~/Content/Banner/" + postedFile.FileName + extension);
postedFile.SaveAs(filePath);
return new HttpResponseMessage()
{
StatusCode = HttpStatusCode.Created,
Content = new StringContent(filePath, Encoding.UTF8, "application/json")
};
}
Now, you have the filepath in the content of the API response.
and use that response like :
var displayBannersDto = new DisplayBannersDto();
displayBannersDto.Banner_Location = response.Content.ToString();
then call your AddBanner() API with displayBannersDto as the dto.

Categories