how to open filecontentresult without window prompt in any browser - asp.net-mvc

I have filecontentresult from controller action method as shown ,contents is byte[] type
FileContentResult file= new FileContentResult(contents, "/PDF");
Response.AppendHeader("Content-Disposition", "inline; filename=" + filename);
return file;
Now, if the file type is known as pdf and specified, why is not directly opening in adobe reader and prompting window to openwith /saveas. If my filecontentresult passes pdf I want it to open without window propmt. how can it be done? Also the above code only prompting window in mozilla, In IE no prompt or opening.

The trick is in content type, you've set it worng. If browser knows how to handle that content type it will open it:
public ActionResult GetPDF()
{
var path = #"C:\Test\Testing.pdf";
var contents = System.IO.File.ReadAllBytes(path);
return File(contents, "application/pdf");
}

The answer in one line.
return new FileContentResult(documentModel.DocumentData, documentModel.DocumentMediaType);
And to put it into context here is the DocumentSave...
private bool SaveDocument(DwellingDocumentModel doc, HttpPostedFileBase files)
{
if (Request.Files[0] != null)
{
byte[] fileData = new byte[Request.Files[0].InputStream.Length];
Request.Files[0].InputStream.Read(fileData, 0, Convert.ToInt32(Request.Files[0].InputStream.Length));
doc.DocumentData = fileData;
doc.DocumentMediaType = Request.Files[0].ContentType;
}
if (doc.Save())
{
return true;
}
return false;
}

Related

Cannot open file after downloading from Server

After downloaded a file from Server (pdf, jpg,..) successfully, I couldn't open that file in my computer.
It said "It looks like we don't support this file format". Files are stored and readable on Server.
Wonder if there is something missing in my Download Function:
[HttpGet]
public ActionResult Download(Guid? attachmentId)
{
var visitAttachment = _visitAttachmentService.FindOne(x => x.Id == attachmentId);
try
{
var serverPath = Server.MapPath(visitAttachment.Path);
byte[] fileBytes = System.IO.File.ReadAllBytes(serverPath);
return File(fileBytes, System.Net.Mime.MediaTypeNames.Application.Octet, visitAttachment.AttachmentName);
}
catch
{
return File(Encoding.UTF8.GetBytes(""), System.Net.Mime.MediaTypeNames.Application.Octet, visitAttachment.AttachmentName);
}
}
It seems like file not downloaded properly, try this, may it help, good luck
FileDownload(yourfilepath ,yourfilenamewithFormat)
{
string filename = yourfilenamewithFormat;
byte[] file_Bytes = System.IO.File.ReadAllBytes(yourfilepath);
return File(file_Bytes, System.Net.Mime.MediaTypeNames.Application.Octet, filename);
}
My opinion, is that you can be missing the file extension. If that is the case you can get it by the using Path.GetExtension(serverPath)
Edited
Try to use FileResult instead of ActionResult
[HttpGet]
public FileResult Download(Guid? attachmentId)
{
var visitAttachment = _visitAttachmentService.FindOne(x => x.Id == attachmentId);
try
{
var serverPath = Server.MapPath(visitAttachment.Path);
byte[] fileBytes = System.IO.File.ReadAllBytes(serverPath);
return File(fileBytes, System.Net.Mime.MediaTypeNames.Application.Octet, visitAttachment.AttachmentName);
}
catch
{
return File(Encoding.UTF8.GetBytes(""), System.Net.Mime.MediaTypeNames.Application.Octet, visitAttachment.AttachmentName);
}
}

Write zip files to MemoryStream

I have a controller action that creates a zip file and sends back to user for download. The problem is that the zip file gets created but it is empty. Somehow it's not writing the image files to the MemoryStream. I wonder what I am missing. If I write the zip file to the disk everything will work as expected, but I'd rather not save files to the disk if I can avoid it. This is what I have tried using dotnetzip:
public ActionResult DownloadGraphs()
{
var state = Session["State"];
using (ZipFile zip = new ZipFile())
{
if (state == "IA")
{
zip.AddFile(Server.MapPath("~/Content/DataVizByState/FallGraphs/Watermarked/Fall_IA.jpg"), "");
zip.AddFile(Server.MapPath("~/Content/DataVizByState/SpringGraphs/Watermarked/Spring_IA.jpg"), "");
}
MemoryStream output = new MemoryStream();
zip.Save(output);
output.Seek(0, SeekOrigin.Begin);
var fileName = state + "Graphs.zip";
return File(output, "application/zip", fileName);
}
}
This forces download in the view based on click of a button:
$('#graphDwnldBtn').click(function (evt) {
window.location = '#Url.Action("DownloadGraphs", "DataSharing")';
})
Do I need to use StreamWriter or Reader or something? This is the first time I have ever attempted something like this and it's been cobbled together by reading various stackoverflow posts...
Dumb mistakes: Session["State"] is an object, so the state variable was coming out as object instead of a string like I need it to be for my conditional statement to evaluate correctly. I cast state to a string to fix it. Fixed code:
public ActionResult DownloadGraphs()
{
var state = Session["State"].ToString();
using (ZipFile zip = new ZipFile())
{
if (state == "IA")
{
zip.AddFile(Server.MapPath("~/Content/DataVizByState/FallGraphs/Watermarked/Fall_IA.jpg"), "");
zip.AddFile(Server.MapPath("~/Content/DataVizByState/SpringGraphs/Watermarked/Spring_IA.jpg"), "");
}
MemoryStream output = new MemoryStream();
zip.Save(output);
output.Seek(0, SeekOrigin.Begin);
var fileName = state + "Graphs.zip";
return File(output, "application/zip", fileName);
}
}

Export data to excel with EPPlus and WebApi

I'm trying to export a list, but when i open the file download it just shows a bunch of characteres that don't make sense (kinda looks like machine language). I've looked at some codes here and all of them are similar to mine, what am I missing?
Here's my code:
The method I call:
[HttpGet]
public HttpResponseMessage Get()
{
HttpResponseMessage response;
response = Request.CreateResponse(HttpStatusCode.OK);
MediaTypeHeaderValue mediaType = new MediaTypeHeaderValue("application/ms-excel");
response.Content = new StreamContent(GetExcelSheet());
response.Content = response.Content;
response.Content.Headers.ContentType = mediaType;
response.Content.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment");
response.Content.Headers.ContentDisposition.FileName = "PivotGrid_Orders.xls";
return response;
}
The method that format cells:
public MemoryStream GetExcelSheet()
{
using (var package = new ExcelPackage())
{
var worksheet = package.Workbook.Worksheets.Add("Orders");
//worksheet.Cells["A1"].LoadFromCollection()
worksheet.Cells["A1"].LoadFromCollection(Orders(), false);
package.Save();
var stream = new MemoryStream(package.GetAsByteArray()); //capacidade
return stream;
}
}
The list i've created to test:
public List<ExListModel> Orders()
{
List<ExListModel> lst = new List<ExListModel>();
orders.Add(new ExListModel{ Nome = "Developer"});
return lst;
}
As I didn't know EPPlus, I googled it, and its Github page states it produces Open XML excel files (.xlsx). You produce the file with an extension and mimetype of the old binary excel filetype. Change the contenttype to application/vnd.openxmlformats-officedocument.spreadsheetml.sheet and the filename extension to xlsx.

MVC IE8 with Chrome Frame double post when return csv file

I want to create and return a CSV file from a controller but I have several errors in IE8 with Chrome frame, because the controller returns a file and again calls post two times.
In my view I have a simple submit button:
Controller:
public ActionResult File()
{
string billcsv = "account_ref,line1,line2,line3";
var data = Encoding.UTF8.GetBytes(billcsv);
string filename = "billfor.csv";
var cd = new System.Net.Mime.ContentDisposition();
cd.FileName = "filename.csv";
//Response.AddHeader("Content-Disposition", cd.ToString());
Response.AddHeader("Content-Disposition", "attachment;filename=filename.csv");
return File(data, "text/csv", filename);
}
Thanks.
Try this:
public FileResult File()
{
string billcsv = "account_ref,line1,line2,line3";
var data = Encoding.UTF8.GetBytes(billcsv);
string filename = "billfor.csv";
File(data, System.Net.Mime.MediaTypeNames.Application.Octet, filename);
}

ASP MVC Download Zip Files

i have a view where i put the id of the event then i can download all the images for that event.....
here's my code
[HttpPost]
public ActionResult Index(FormCollection All)
{
try
{
var context = new MyEntities();
var Im = (from p in context.Event_Photos
where p.Event_Id == 1332
select p.Event_Photo);
Response.Clear();
var downloadFileName = string.Format("YourDownload-{0}.zip", DateTime.Now.ToString("yyyy-MM-dd-HH_mm_ss"));
Response.ContentType = "application/zip";
Response.AddHeader("content-disposition", "filename=" + downloadFileName);
using (ZipFile zipFile = new ZipFile())
{
zipFile.AddDirectoryByName("Files");
foreach (var userPicture in Im)
{
zipFile.AddFile(Server.MapPath(#"\") + userPicture.Remove(0, 1), "Files");
}
zipFile.Save(Response.OutputStream);
//Response.Close();
}
return View();
}
catch (Exception ex)
{
return View();
}
}
The problem is that each time i get html page to download so instead of downloading "Album.zip" i get "Album.html" any ideas???
In MVC, rather than returning a view, if you want to return a file, you can return this as an ActionResult by doing:
return File(zipFile.GetBytes(), "application/zip", downloadFileName);
// OR
return File(zipFile.GetStream(), "application/zip", downloadFileName);
Don't mess about with manually writing to the output stream if you're using MVC.
I'm not sure if you can get the bytes or the stream from the ZipFile class though. Alternatively, you might want it to write it's output to a MemoryStream and then return that:
var cd = new System.Net.Mime.ContentDisposition {
FileName = downloadFileName,
Inline = false,
};
Response.AppendHeader("Content-Disposition", cd.ToString());
var memStream = new MemoryStream();
zipFile.Save(memStream);
memStream.Position = 0; // Else it will try to read starting at the end
return File(memStream, "application/zip");
And by using this, you can remove all lines in which you are doing anything with the Response. No need to Clear or AddHeader.

Resources