I have written some Asp.Net MVC code that returns an Html file FileResult.
var stream = new MemoryStream();
var writer = new StreamWriter(stream);
writer.Write(htmlReport);
writer.Flush();
stream.Position = 0;
return File(stream, "text/html", fileName);
Using my local environment the HTML file looks fine when opened but after deploying to the server and downloading the same file some unwanted  characters can be seen. How could the difference in server environments be affecting a file which is downloaded to the users pc?
You need to specify the file encoding. You are most likely using UTF8, but other formats are available.
var writer = new StreamWriter(stream, System.Text.Encoding.UTF8);
Why use the StreamWriter at all?
return Content(htmlReport, "text/html", System.Text.Encoding.UTF8);
Or if you want to be using File as your return result try:
byte[] bArray = System.Text.Encoding.UTF8.GetBytes(htmlReport);
return File(bArray, "text/html", fileName);
Related
I am using NPOI to save files to an .xls format.
I would like to save an empty file for now that a user has a dialog box and is prompted to save it locally.
The problem I have is I cannot set the Response fields, because
The name 'Response' does not exist in the current context.
This is the class I want to use:
https://learn.microsoft.com/en-us/dotnet/api/system.web.httpresponse?view=netframework-4.8
//Load all documents sorted by DocNumber and export them
var documents = await _ctx.Db.Documents
.AsNoTracking()
.OrderByDescending(d => d.Number)
.ToListAsync();
var workbook = new HSSFWorkbook();
var sheet = workbook.CreateSheet("Invoicing_Docs");
using (var exportData = new MemoryStream())
{
workbook.Write(exportData);
string saveAsFileName = string.Format("Invoicing_Docs-{0:d}.xls", DateTime.UtcNow).Replace("/", "-");
Response.ContentType = "application/vnd.ms-excel";
Response.AddHeader("Content-Disposition", string.Format("attachment;filename={0}", saveAsFileName));
Response.Clear();
Response.BinaryWrite(exportData.GetBuffer());
Response.End();
}
I have installed System.Web in the project.
When I ctrl + . on Response I have 3 choices:
Install package "IdentityMode",
Install package "Selenium.WebDriver"
Install package "Swashbuckle.AspNetCore.Swagger"
Also this is the article, I am following:
https://steemit.com/utopian-io/#haig/how-to-create-excel-spreadsheets-using-npoi
I don't need any of those. What am I doing wrong?
I found out what I need to do.
I was not using the controller I was writing a service that is called in the controller.
All I had to do is inject Response in the Method of the service.
I have a project ASP.NET Core 2.0 MVC running on IIS.
Want to Export some information from data grid to Excel and save it from web page to the desktop of current user.
string fileName = "SN-export-" + DateTime.Now + ".xlsx";
Regex rgx = new Regex("[^a-zA-Z0-9 -]");
fileName = rgx.Replace(fileName, ".");
string path = Environment.GetFolderPath(Environment.SpecialFolder.Desktop);
string fileName2 = Path.Combine(path, fileName);
FileInfo excelFile = new FileInfo(fileName2);
excel.SaveAs(excelFile);
This works perfect local at Visual Studio, but not after publishing at IIS.
Using simple path string path = #"C:\WINDOWS\TEMP"; It will save this export file at the server temp folder, but not current web page user.
How to get this?
ASP.NET MVC is framework for a web application. So you have fronted and backend parts. This code will executed on the server side of your application. Even if you use Razor pages, they also generated at the backend. So there are several ways to save data on the computer:
use js to iterate data and save it, but I'm not sure that saving to excel with js is easy;
send desired data to backend, save it to excel and then return to the client.
For a second way you can use next code:
[Route("api/[controller]")]
public class DownloadController : Controller {
//GET api/download/12345abc
[HttpGet("{id}"]
public async Task<IActionResult> Download(YourData data) {
Stream stream = await {{__get_stream_based_on_your_data__}}
if(stream == null)
return NotFound();
return File(stream, "application/octet-stream"); // returns a FileStreamResult
}
}
And because of security reasons you can save data only to downloads directory.
VS 2013, MVC application need to download files from the particular drive. i have written the below code. All the files are displayed in the grid. below hard coded the path but still not able to download the file
[HttpPost]
public FileResult downloadlogfiles(string logfilename)
{
byte[] fileBytes = System.IO.File.ReadAllBytes(#"d:\Logs\try.txt");
string fileName = "myfile.ext";
return File(fileBytes, System.Net.Mime.MediaTypeNames.Application.Octet, fileName);
}
I create name file for download file:
string fileName = Resources.Resource.VacationLimits + year + ".xlsx";
When aplication run on localhost - I can normal download file.
After build as Release and publish Web on server,
when I download file I have wrong file name without the file extension .xlsx in IE. In other browser I can download file with correct name and the file extension .xlsx.
all method:
MemoryStream stream;
var result = vacationService.GetVacationFile(out stream);
string fileName = Resources.Resource.VacationLimits + year + ".xlsx";
const string contentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
return File(stream, contentType, fileName);
I have an ASP.NET MVC2 application in development and I am having problems rendering a .pdf file from our production server.
On my Visual Studio 2010 integrated development server everything works fine, but after I publish the application to the production server, it breaks. It does not throw any exceptions or errors of any kind, it simply does not show the file.
Here's my function for displaying the PDF document:
public static void PrintExt(byte[] FileToShow, String TempFileName,
String Extension)
{
String ReportPath = Path.GetTempFileName() + '.' + Extension;
BinaryWriter bwriter =
new BinaryWriter(System.IO.File.Open(ReportPath, FileMode.Create));
bwriter.Write(FileToShow);
bwriter.Close();
System.Diagnostics.Process p = new System.Diagnostics.Process();
p.StartInfo.FileName = ReportPath;
p.StartInfo.UseShellExecute = true;
p.Start();
}
My production server is running Windows Server 2008 and IIS 7.
You cannot expect opening the default program associated with PDF file browsing on the server. Try returning the file into the response stream which will effectively open it on the client machine:
public ActionResult ShowPdf()
{
byte[] fileToShow = FetchPdfFile();
return File(fileToShow, "application/pdf", "report.pdf");
}
And now navigate to /somecontroller/showPdf. If you want the PDF opening inside the browser instead of showing the download dialog you may try adding the following to the controller action before returning:
Response.AddHeader("Content-Disposition", "attachment; filename=report.pdf");
i suggest you use ASP.NET MVC FileResult Class to display the PDF.
see http://msdn.microsoft.com/en-us/library/system.web.mvc.fileresult.aspx
your code open`s the PDF on the webserver.
Here's how I did it.
public ActionResult PrintPDF(byte[] FileToShow, String TempFileName, String Extension)
{
String ReportPath = Path.GetTempFileName() + '.' + Extension;
BinaryWriter bwriter = new BinaryWriter(System.IO.File.Open(ReportPath, FileMode.Create));
bwriter.Write(FileToShow);
bwriter.Close();
return base.File(FileToShow, "application/pdf");
}
Thank you all for your efforts. Solution I used is the most similar to the Darin's one (almost the same, but his is prettier :D), so I will accept his solution.
Vote up for all of you folks (both for answers and comments)
Thanks