Unable to download Excel file when call from Postman - c#

I am trying to download Excel file using web API but I am unable to download file in postman where as I am able to download Excel file when I enter URL in browser though while opening file I get warning message like below :
When i hit endpoint using POSTMAN then file get corrupted and it is showing junk characters.
Code :
protected virtual byte[] ExportToXlsx<T>(IEnumerable<T> itemsToExport)
{
using (var stream = new MemoryStream())
{
using (var xlPackage = new ExcelPackage())
{
// get handles to the worksheets
var worksheet = xlPackage.Workbook.Worksheets.Add(typeof(T).Name);
//create Headers and format them
var manager = new PropertyManager<T>(itemsToExport.First());
manager.WriteCaption(worksheet, SetCaptionStyle);
var row = 2;
foreach (var items in itemsToExport)
{
manager.CurrentObject = items;
manager.WriteToXlsx(worksheet, row++, false);
}
xlPackage.Save();
}
return stream.ToArray();
}
}
private readonly IServiceContext ctx;
public void Download(string guid)
{
var bytes = ExportToXlsx(list);
ctx.reqobj.HttpContext.Response.Headers.Add("Content-Disposition", "attachment; filename=\"demo.xlsx\"");
ctx.reqobj.HttpContext.Response.ContentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
ctx.reqobj.HttpContext.Response.Body.Write(bytes, 0, bytes.Length);
}
Note : I am using OfficeOpenXml for Excel file creation.
I will appreciate any help.
Update :

Try using "Send and download" instead of "Send"
https://www.getpostman.com/docs/v6/postman/sending_api_requests/responses

Postman doesn't download any file just return you the data that the server or your service provides. i have a project that download an excel to with the OpenXML here is an example with which you can guide with some styles to.
[HttpGet]
public void DownloadTable(int id)
{
List<Employee> all = db.Employees.Where(x => x.ManagerId == id).ToList();
String file = "Example.xlsx";
String path = Path.Combine(HttpContext.Current.Server.MapPath("~/App_Data"), file);
List<string[]> headerRow = new List<string[]>() { new string[] { "EmployeeId", "Name", "Shift", "Timestamp" } };
string headerRange = "A2:" + Char.ConvertFromUtf32(headerRow[0].Length + 64) + "2";
ExcelPackage excel = new ExcelPackage();
excel.Workbook.Worksheets.Add("Employees");
var page = excel.Workbook.Worksheets["Employees"];
page.Cells["A1:D1"].Merge = true;
page.Cells["A1:D1"].Value = "Supervisor: " + all.FirstOrDefault().Manager + " - " + id;
page.Cells["A1:D1"].Style.Font.Bold = true;
page.Cells[headerRange].LoadFromArrays(headerRow);
int z = 3;
foreach (Reporte r in all)
{
page.Cells["A" + z].Value = r.Id;
page.Cells["B" + z].Value = r.Name;
page.Cells["C" + z].Value = r.Shift;
page.Cells["D" + z].Value = r.Timestamp;
z++;
}
page.Cells["D3:D" + z].Style.Numberformat.Format = "dddd dd MMMM YYYY";
page.Cells["A2:D2"].AutoFilter = true;
page.Cells["A1:D" + z].Style.HorizontalAlignment = ExcelHorizontalAlignment.Center;
page.Cells["A1:D" + z].Style.VerticalAlignment = ExcelVerticalAlignment.Center;
page.Cells["A2:D" + z].AutoFitColumns();
page.Cells["A1:D1"].Style.Fill.PatternType = ExcelFillStyle.Solid;
page.Cells["A1:D1"].Style.Fill.BackgroundColor.SetColor(Color.FromArgb(1, 183, 222, 232));
FileInfo excelFile = new FileInfo(path);
excel.SaveAs(excelFile);
System.Web.HttpResponse response = System.Web.HttpContext.Current.Response;
response.ClearContent();
response.Clear();
response.ContentType = "text/plain";
response.AddHeader("Content-Disposition",
"attachment; filename=" + file + ";");
response.TransmitFile(path);
response.Flush();
response.End();
File.Delete(path);
}

The stream needs to be passed to the package.
Right now nothing is being given to the package,
//...
using (var xlPackage = new ExcelPackage())
//...
So nothing is being saved to the stream, which is why the error is shown when trying to open the file.
There is no need to convert the memory stream to an array. Return the stream and pass that along for the response.
protected virtual Stream ExportToXlsx<T>(IEnumerable<T> itemsToExport) {
var stream = new MemoryStream();
using (var xlPackage = new ExcelPackage(stream)) { //<<< pass stream
// get handles to the worksheets
var worksheet = xlPackage.Workbook.Worksheets.Add(typeof(T).Name);
//create Headers and format them
var manager = new PropertyManager<T>(itemsToExport.First());
manager.WriteCaption(worksheet, SetCaptionStyle);
var row = 2;
foreach (var items in itemsToExport) {
manager.CurrentObject = items;
manager.WriteToXlsx(worksheet, row++, false);
}
xlPackage.Save();
}
return stream;
}
A controller action to return the file would look like this
public IActionResult Download(string guid) {
//...get list
var file = ExportToXlsx(list);
var contentType = "application/vnd.openxmlformats";
var fileName = "demo.xlsx";
return File(file, contentType, fileName); //returns a FileStreamResult
}
It was indicated in comments that the above is done in a support method.
Using the same approach
private readonly IServiceContext ctx;
//...
public void Download(string guid) {
//...get list
using(var fileStream = ExportToXlsx(list)) {
if (fileStream.CanSeek && fileStream.Position != 0) {
fileStream.Seek(0, SeekOrigin.Begin);
}
var contentType = "application/vnd.openxmlformats";
var fileName = "demo.xlsx";
var response = ctx.reqobj.HttpContext.Response;
response.Headers.Add("Content-Disposition", $"attachment; filename=\"{fileName}\"");
response.Headers.Add("Content-Length", fileStream.Length.ToString());
response.ContentType = contentType;
fileStream.CopyTo(response.Body);
}
}
the generated file is copied over to the body of the response.
As for postman, the tool is simply showing the content return in the response. It does not try to download the actual file as an attachment.

Related

FileContentResult return excel file corrupt

I am trying to download an xlsx file from an ftp but when I download and try to open it I get that it is a corrupt file. . I share the back and front code.
public async Task<TransacResult> DownloadFileInterface(Uri serverUri, string fileName)
{
StreamReader sr;
byte[] fileContent;
try
{
string ftpUser = GetConfiguration()["SuatKeys:FTPSuatUser"];
string ftpPassword = GetConfiguration()["SuatKeys:FTPSuatPassword"];
FtpWebRequest request = (FtpWebRequest)WebRequest.Create(serverUri);
request.Method = WebRequestMethods.Ftp.DownloadFile;
request.KeepAlive = false;
request.Credentials = new NetworkCredential(ftpUser, ftpPassword);
sr = new StreamReader(request.GetResponse().GetResponseStream());
fileContent = Encoding.UTF8.GetBytes(sr.ReadToEnd());
sr.Close();
sr.Dispose();
FtpWebResponse response = (FtpWebResponse)await request.GetResponseAsync();
var fileContentResult = new FileContentResult(fileContent, "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet")
{
FileDownloadName = fileName + ".xlsx"
};
return new TransacResult(true, fileContentResult);
}
catch (Exception ex)
{
return new TransacResult(false, new Message("SUAT-ERR-C02", MessageCategory.Error, "Conexión rechazada", ex.Message));
}
}
async downloadlayout() {
var obj = this.interfaces.item;
if (this.$store.state.usuarioActivo.modeD == 0)
obj = serialize(obj);
const res = await this.$store.dispatch("apiPost", {
url: "Interface/DownloadDinamycLayout",
item: obj
})
console.clear();
console.log(res);
const a = document.createElement("a");
a.href = "data:application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;base64," + res.fileContents;
a.download = res.fileDownloadName;
a.click();
a.remove();
},
reading the file does not present any problem
Greetings
Assuming you the file on FTP isn't corrupted, the problem have is that .xlsx files are not textual files, but StreamReader is intended for reading text. Using it as you are will corrupt arbitrary binary data (e.g. an .xlsx file).
I would personally just stream the file from FTP, through your server, and straight to the client:
public async Task<TransacResult> DownloadFileInterface(Uri serverUri, string fileName)
{
StreamReader sr;
byte[] fileContent;
try
{
string ftpUser = GetConfiguration()["SuatKeys:FTPSuatUser"];
string ftpPassword = GetConfiguration()["SuatKeys:FTPSuatPassword"];
FtpWebRequest request = (FtpWebRequest)WebRequest.Create(serverUri);
request.Method = WebRequestMethods.Ftp.DownloadFile;
request.KeepAlive = false;
request.Credentials = new NetworkCredential(ftpUser, ftpPassword);
Stream ftpFileStream = request.GetResponse().GetResponseStream();
var fileContentResult = new FileStreamResult(ftpFileStream, "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet")
{
FileDownloadName = fileName + ".xlsx"
};
return new TransacResult(true, fileContentResult);
}
catch (Exception ex)
{
return new TransacResult(false, new Message("SUAT-ERR-C02", MessageCategory.Error, "Conexión rechazada", ex.Message));
}
}
I tried three times with two Actions:
[HttpPost]
public FileResult download(IFormFile file)
{
var filestream = file.OpenReadStream();
var filestreamreader = new StreamReader(filestream, Encoding.Default);
var fileContent1 = Encoding.Default.GetBytes(filestreamreader.ReadToEnd());
return File(fileContent1, "application/ms-excel", "3.xlsx");
}
[HttpPost]
public FileResult download1(IFormFile file)
{
var filestream = file.OpenReadStream();
ExcelPackage.LicenseContext = LicenseContext.NonCommercial;
ExcelPackage package = new ExcelPackage(filestream);
var fileContent = package.GetAsByteArray();
return File(fileContent, "application/ms-excel", "3.xlsx");
}
At First,I tried to read the content of txt file and xlsx file ,you could see we could get the content string of txt file,but failed to get the string in xlsx file
Then I tried to get the content byte from stream again with EPPlus and succeeded
The ResulT:
The reason I recomanded EEplus: If Oneday we want to download the xlsx file with some extra infomation,we could just add some codes rather than delet the codes and write again
codes as below;
[HttpPost]
public FileResult download1(IFormFile file)
{
var employeelist = new List<Employee>()
{
new Employee(){Id=1,Name="Jhon",Gender="M",Salary=5000},
new Employee(){Id=2,Name="Graham",Gender="M",Salary=10000},
new Employee(){Id=3,Name="Jenny",Gender="F",Salary=5000}
};
var stream = file.OpenReadStream();
byte[] fileContent;
ExcelPackage.LicenseContext = LicenseContext.NonCommercial;
using (ExcelPackage package = new ExcelPackage(stream))
{
// add a new worksheet to the empty workbook
ExcelWorksheet worksheet = package.Workbook.Worksheets.Add("Employee");
//Set the Width and Height
//worksheet.Column(1).Width = xx;
//worksheet.Row(1).Height = xx;
//Add the headers
worksheet.Cells[1, 1].Value = "ID";
worksheet.Cells[1, 2].Value = "Name";
worksheet.Cells[1, 3].Value = "Gender";
worksheet.Cells[1, 4].Value = "Salary (in $)";
for(int i=0; i< employeelist.Count; i++)
{
worksheet.Cells[i + 2, 1].Value = employeelist[i].Id;
worksheet.Cells[i + 2, 2].Value = employeelist[i].Name;
worksheet.Cells[i + 2, 3].Value = employeelist[i].Gender;
worksheet.Cells[i + 2, 4].Value = employeelist[i].Salary;
}
package.Save(); //Save the workbook.
fileContent = package.GetAsByteArray();
}
return File(fileContent, "application/ms-excel", "target.xlsx");
}
The Result:

How to download an excel in a chrome browser having options as Open, Save and Cancel as i used closed Xml in C#?

How to download an excel in a chrome browser having options as Open, Save and Cancel as I used closed Xml in C#?
public FileResult ExportToExcel(List<MyStudentList_Result> StudentList)
{
List<string[]> titles = new List<string[]> { new string[] { "name", "Number", "Type", "syllabus", "Title", "Added" } };
byte[] fileStream = ExportToExcel(StudentList, "StudentList", titles);
string mimeType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
Response.AppendHeader("Content-Disposition", "inline; filename=" + "StudentList.xlsx");
return File(fileStream, mimeType);
}
public byte[] ExportToExcel(List<MystudentList_Result> StudentList, string worksheetTitle, List<string[]> titles)
{
var wb = new XLWorkbook(); //create workbook
var ws = wb.Worksheets.Add(worksheetTitle); //add worksheet to workbook
var rangeTitle = ws.Cell(1, 1).InsertData(titles); //insert titles to first row
rangeTitle.AddToNamed("Titles");
var titlesStyle = wb.Style;
titlesStyle.Font.Bold = true; //font must be bold
// titlesStyle.Alignment.Horizontal = XLAlignmentHorizontalValues.Center; //align text to center
wb.NamedRanges.NamedRange("Titles").Ranges.Style = titlesStyle; //attach style to the range
if (StudentList!= null && StudentList.Count() > 0)
{
//insert data to from second row on
ws.Cell(2, 1).InsertData(StudentList);
ws.Columns().AdjustToContents();
}
//save file to memory stream and return it as byte array
using (var ms = new MemoryStream())
{
wb.SaveAs(ms);
return ms.ToArray();
}
}
You can guide what the browser does with the Content-Disposition header. For saving the file you should use attachment:
Response.AddHeader("content-disposition", "attachment; filename=" + fileName);

Convert LINQ result to CSV or Excel

Using a LINQ query I need to export to Excel when a WebApi method is called. I have built the LINQ query that will return the correct data, now I need it to export to .csv or Excel file format.
I have tried using MemoryStream and StreamWriter but I think I am just chasing my tail now.
[HttpGet]
[Route("Download")]
public Task<IActionResult> Download(int memberId)
{
var results = (from violations in _db.tblMappViolations
where violations.MemberID == memberId
select new IncomingViolations
{
Contact = violations.ContactName,
Address = violations.str_Address,
City = violations.str_City,
State = violations.str_State,
Zip = violations.str_Zipcode,
Country = violations.str_Country,
Phone = violations.str_Phone,
Email = violations.str_Email,
Website = violations.str_WebSite,
}).FirstOrDefault();
MemoryStream stream = new MemoryStream(results);
StreamWriter writer = new StreamWriter(stream);
writer.Flush();
stream.Position = 0;
FileStreamResult response = File(stream, "application/octet-stream");
response.FileDownloadName = "violations.csv";
return response;
}
Here is how you can send CSV file to the user from server.
string attachment = "attachment; filename=MyCsvLol.csv";
HttpContext.Current.Response.Clear();
HttpContext.Current.Response.ClearHeaders();
HttpContext.Current.Response.ClearContent();
HttpContext.Current.Response.AddHeader("content-disposition", attachment);
HttpContext.Current.Response.ContentType = "text/csv";
HttpContext.Current.Response.AddHeader("Pragma", "public");
var sb = new StringBuilder();
// Add your data into stringbuilder
sb.Append(results.Contact);
sb.Append(results.Address);
sb.Append(results.City);
// and so on
HttpContext.Current.Response.Write(sb.ToString());
For Sending it from API
MemoryStream stream = new MemoryStream();
StreamWriter writer = new StreamWriter(stream);
// Write Your data here in writer
writer.Write("Hello, World!");
writer.Flush();
stream.Position = 0;
HttpResponseMessage result = new HttpResponseMessage(HttpStatusCode.OK);
result.Content = new StreamContent(stream);
result.Content.Headers.ContentType = new MediaTypeHeaderValue("text/csv");
result.Content.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment") { FileName = "Export.csv" };
return result;
Update:-
public HttpResponseMessage Download()
{
var results = (from violations in _db.tblMappViolations
where violations.MemberID == memberId
select new IncomingViolations
{
Contact = violations.ContactName,
Address = violations.str_Address,
City = violations.str_City,
State = violations.str_State,
Zip = violations.str_Zipcode,
Country = violations.str_Country,
Phone = violations.str_Phone,
Email = violations.str_Email,
Website = violations.str_WebSite,
});
var sb = new StringBuilder();
MemoryStream stream = new MemoryStream();
StreamWriter writer = new StreamWriter(stream);
foreach(var tempResult in results)
{
sb.Append(tempResult.Contact+",");
sb.Append(tempResult.Address+",");
sb.Append(tempResult.City+",");
sb.Append(tempResult.State+",");
sb.Append(tempResult.Zip+",");
sb.Append(tempResult.Country+",");
sb.Append(tempResult.Phone+",");
sb.Append(tempResult.Email+",");
sb.Append(tempResult.Website+",");
sb.Append(Enviroment.NewLine);
}
writer.Write(sb.ToString());
writer.Flush();
stream.Position = 0;
HttpResponseMessage result = new HttpResponseMessage(HttpStatusCode.OK);
result.Content = new StreamContent(stream);
result.Content.Headers.ContentType = new MediaTypeHeaderValue("text/csv");
result.Content.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment") { FileName = "Export.csv" };
return result;
}
First, to reuse the code in other areas, always create helper classes.
I adopted this method of converting list into a stream with headers as property names, if you want a file from this, essentially, I would just add another step to this:
STEP 1:
public static Stream ConvertToCSVStream<T>(IEnumerable<T> objects)
{
Type itemType = typeof(T);
var properties = itemType.GetProperties();
var mStream = new MemoryStream();
StreamWriter sWriter = new StreamWriter(mStream);
var values = objects.Select(o =>
{
return string.Join(",", properties.Select(p =>
{
var value = p.GetValue(o).ToString();
if (!Regex.IsMatch(value, "[,\"\\r\\n]"))
{
return value;
}
value = value.Replace("\"", "\"\"");
return string.Format("\"{0}\"", value);
})) + sWriter.NewLine;
});
var valuesInStrings = values.Aggregate((current, next) => current + next);
try
{
sWriter.Write(string.Join(",", properties.Select(x => x.Name.Replace("_", " "))) + sWriter.NewLine);
sWriter.Write(valuesInStrings);
}
catch (Exception e)
{
mStream.Close();
throw e;
}
sWriter.Flush();
mStream.Position = 0;
return mStream;
}
if your data is text, just convert it directly to a file result but if not, you must convert it to binary array and write it to stream, refer to this article for converting it to binary data, in our case, for csv, you could just use the FileStream result that you've implemented in a separate method:
STEP 2:
public FileStreamResult CreateFile(MemoryStream mStream, string path, string name)
{
//set values, names, content type, etc
//return filestream
}
or any other method you find better.
Save your result in a DataTable and then just use this
XLWorkbook workbook = new XLWorkbook();
DataTable table = GetYourTable();
workbook.Worksheets.Add(table);
And you should definitely use stream writer for this if you know which file its going to write to from the start, else stream reader and then stream writer.

how to remove content from images when using multipart

so I made an uploader in my web API by using multipart form data but the problem is when I save my pictures from the file stream it also gave me the content here
-----------------------------7e1e364095c
Content-Disposition: form-data; name="file"; filename="C:\Users\kewin\Downloads\windows 10 pro.jpg"
Content-Type: image/jpeg
the binary starts from here
and if i remove thoose 4 lines i can watch my picture so are there any way to remove that so I am only left with the picture
public async Task<IHttpActionResult> UploadImage(string fileName = "")
{
if (fileName == "")
{
fileName = Guid.NewGuid().ToString();
}
if (!Request.Content.IsMimeMultipartContent("form-data"))
{
return BadRequest("Could not find file to upload");
}
var provider = await Request.Content.ReadAsMultipartAsync(new InMemoryMultipartFormDataStreamProvider());
var files = provider.Files;
var uploadedFile = files[0];
var extension = ExtractExtension(uploadedFile);
var contentType = uploadedFile.Headers.ContentType.ToString();
var savePath = ConfigurationManager.AppSettings["savePath"];
var file = string.Concat(savePath, fileName, extension);
try
{
var request = HttpContext.Current.Request;
var fileDir = file + request.Headers[""];
using (var fs = new FileStream(fileDir, FileMode.Create))
{
request.InputStream.CopyTo(fs);
}
return Ok();
}
catch (StorageException e)
{
return BadRequest(e.Message);
}
try
{
var fileInfo = new UploadedFileInfo
{
FileName = fileName,
FileExtension = extension,
ContentType = contentType,
FilePath = savePath + imageFile
};
return Ok(fileInfo);
}
Currently you read picture data from request.InputStream, which contains whole unparsed multipart content, including headers you don't need. Instead, you should read picture data from InMemoryMultipartFormDataStreamProvider you created, which parses input stream and provides you simple access to headers and data stream of individual uploaded file(s).
....
var provider = await Request.Content.ReadAsMultipartAsync(new InMemoryMultipartFormDataStreamProvider());
var files = provider.Files;
var uploadedFile = files[0];
var extension = ExtractExtension(uploadedFile);
var contentType = uploadedFile.Headers.ContentType.ToString();
var savePath = ConfigurationManager.AppSettings["savePath"];
var file = string.Concat(savePath, fileName, extension);
try
{
using (var fs = new FileStream(file, FileMode.Create))
{
await uploadedFile.CopyToAsync(fs);
}
return Ok();
}
....

Export to CSV in mvc not work

I want to export a list to CSV file using MVC, Jquery. I want to write to a file to the response stream but doesn't do anything. No Download appear.
Below is my code in .cshtml
<button id="btnGenerateCSV">Generate CSV</button>
in .js
$('#btnGenerateCSV').click(function () {
$.post(root + "ClaimInternal/DownloadCsv");
});
In myController
private string GetCsvString(IList<Area> Area)
{
StringBuilder csv = new StringBuilder();
csv.AppendLine("AreaID,AliasName,Description,BankName");
foreach (Area area in Area)
{
csv.Append(area.AreaID + ",");
csv.Append(area.AliasName + ",");
csv.Append(area.Description + ",");
csv.Append(area.BankName + ",");
csv.AppendLine();
}
return csv.ToString();
}
public void DownloadCsv()
{
using (Database db = new Database(_ConnectionString))
{
AreaDAC dacArea = new AreaDAC(db);
List<Area> data = dacArea.Search("", "", "");
string facsCsv = GetCsvString(data);
// Return the file content with response body.
Response.ContentType = "text/csv";
Response.AddHeader("Content-Disposition", "attachment;filename=Area.csv");
Response.Write(facsCsv);
Response.End();
}
}
I try to make like this also
public FileContentResult DownloadCsv()
{
using (Database db = new Database(_ConnectionString))
{
AreaDAC dacArea = new AreaDAC(db);
List<Area> data = dacArea.Search("", "", "");
JsonResult result = new JsonResult();
result.JsonRequestBehavior = JsonRequestBehavior.AllowGet;
result.Data = data;
string facsCsv = GetCsvString(data);
return File(new System.Text.UTF8Encoding().GetBytes(facsCsv), "text/csv", "Area.csv");
}
}
I make also like this
public void DownloadCsv()
{
using (Database db = new Database(_ConnectionString))
{
AreaDAC dacArea = new AreaDAC(db);
List<Area> data = dacArea.Search("", "", "");
string facsCsv = GetCsvString(data);
// Return the file content with response body.
Response.Clear();
Response.Buffer = true;
Response.AddHeader("content-disposition", "attachment;filename=Area.csv");
Response.Charset = "";
Response.ContentType = "application/text";
Response.Output.Write(facsCsv);
Response.Flush();
Response.End();
}
}
But still not work.. No download CSV appear.. While When I got it all working, no error.
Now I already got the answer. I change the script like this and it's work..
var cd = new System.Net.Mime.ContentDisposition
{
FileName = "Area.csv",
Inline = true,
};
Response.AppendHeader("Content-Disposition", cd.ToString());
return File(new System.Text.UTF8Encoding().GetBytes(facsCsv), "text/csv");
It's work by adding new System.Net.Mime.ContentDisposition. But I'm still not understand why.
I was able to do using
window.location = "/urlPath?filename=" + filename;
and in my controller
filename = filename.ToString();
byte[] fileBytes = System.IO.File.ReadAllBytes(filename);
var response = new FileContentResult(fileBytes, "application/octet-stream");
response.FileDownloadName = "Filename.csv";
return response;

Categories