I have a javascript function from which I need to call a controller action to return the filestream to the UI .
I am not getting the open,save and save as dialog box.
In the cshtml file I have following function:DownloadFile
var selectUrl = '#Url.Action("Download", "Controller")' + "/" + filedetails;
$.post(selectUrl);
and in the controller I have the following code:
public ActionResult Download(string id)
return File(downloadStream, "application/octet-stream",fileName);
Please let me know is this the correct way of calling.
try this way :ActionResult
public ActionResult Download(string id)
{
var cd = new System.Net.Mime.ContentDisposition
{
FileName = "imagefilename",
Inline = false,
};
Response.AppendHeader("Content-Disposition", cd.ToString());
string contentType = "application/octet-stream";
// you are downloadStream
return File(downloadStream, contentType);
}
link here
Related
I store few pdf files in my db as binary format using the below code in my controller,
[HttpPost]
public ActionResult Index(HttpPostedFileBase file)
{
Image newImage = new Image();
newImage.MimeType = file.ContentType;
var binaryReader = new BinaryReader(file.InputStream);
newImage.Data = binaryReader.ReadBytes(file.ContentLength);
binaryReader.Close();
objImage.InsertImage(newImage.Data);
return View();
}
now i want to download them back based on the id passed to the contrller that pdf files should be downloaded??
this is my code for pdf download, wat do i need to add more
public ActionResult Download(int id)
{
DataSet da = new DataSet();
da = objImage.getUserImage(id);
DataTable dt = new DataTable();
dt = da.Tables[0];
Byte[] imagedata=(Byte[])dt.Rows[0]["UsImage"];
}
this is my code for pdf download, wat do i need to add more
Return an ActionResult:
public ActionResult Download(int id)
{
...
byte[] imagedata = (byte[])dt.Rows[0]["UsImage"];
return File(imagedata, "image/png");
}
and if you want the browser to popup a Save As dialog instead of displaying the image inline specify a filename:
public ActionResult Download(int id)
{
...
byte[] imagedata = (byte[])dt.Rows[0]["UsImage"];
return File(imagedata, "image/png", "foo.png");
}
Obviously the MIME type and the filename could come from your database as well. In this example I have hardcoded them but you could adapt this code.
return File(result.Content, result.Extension.Replace(".", ""));
public ActionResult Download(int id)
{
DataSet da = new DataSet();
da = objImage.getUserImage(id);
DataTable dt = new DataTable();
dt = da.Tables[0];
Byte[] imagedata=(Byte[])dt.Rows[0]["UsImage"];
return File(imagedata, "image/png");
}
public ActionResult GetPdf(int id)
{
ProjectProfile projectprofile = db.ProjectProfiles.Find(id);
var image = projectprofile.pdf;
return File(image, "application/pdf");
}
Hi I am calling a Handler.ashx from ActionResult
ViewBag.IMG = "Handler.ashx?img=" + imagetest +
, if the ActionResult is Index it works fine,
http://localhost:11111/ImageHandler.ashx?img=image
however if it is any other name, it does not call the Handler!!
http://localhost:11111/ActionReult(name)/ImageHandler.ashx?img=image
It adds the ActionResult name in the url.
Any Idea, thanks in advance.
Then i not understand false, .ashx instead, can use controller in return FileContentResult or FileResult to File or FileStreamResult to File.
Sample
public FileContentResult Index()
{
var Resim = new WebClient().DownloadData("https://dosyalar.blob.core.windows.net/dosya/kartalisveris.gif");
return new FileContentResult(Resim, "image/png"); //* With {.FileDownloadName = "Höbölö"}
}
Or
public FileResult Index()
{
FileInfo fi = new FileInfo(Server.MapPath("~/Content/imgs/fillo_kargo.png"));
return File(fi.OpenRead, "image/png"); //or .FileDownloadName("Eheheh :)") Return File(fi.OpenRead, "audio/mpeg","Media File")
}
so that by variable public
FileResult Index(string picPath)
FileInfo fi = new FileInfo(Server.MapPath("~/Content/imgs/" + picPath +
"));
Url : File/Index/fillo_kargo.png
I just want to generate a pdf document of the details presents in view on button click.
In order to generate a PDF file you will need some third party library as this functionality is not built-in the .NET framework. iTextSharp is a popular one.
So for example you could write a custom action result:
public class PdfResult : ActionResult
{
public override void ExecuteResult(ControllerContext context)
{
var response = context.HttpContext.Response;
response.ContentType = "application/pdf";
var cd = new ContentDisposition
{
Inline = true,
FileName = "test.pdf",
};
response.AddHeader("Content-Disposition", cd.ToString());
using (var doc = new Document())
using (var writer = PdfWriter.GetInstance(doc, response.OutputStream))
{
doc.Open();
doc.Add(new Phrase("Hello World"));
}
}
}
and then have your controller action return this result:
public class HomeController : Controller
{
public ActionResult Index()
{
return new PdfResult();
}
}
I've got a partial view, i'm trying to use ITextSharp to convert the html to pdf. How can I convert the html to string so I can use ItextSharps HtmlParser?
I've tried something like this with no luck...any ideas?:
var contents = System.IO.File.ReadAllText(Url.Action("myPartial", "myController", new { id = 1 }, "http"));
I have created a special ViewResult class that you can return as the result of an Action.
You can see the code on bitbucket (look at the PdfFromHtmlResult class).
So what it basically does is:
Render the view through the Razor engine (or any other registered engine) to Html
Give the html to iTextSharp
return the pdf as the ViewResult (with correct mimetype, etc).
My ViewResult class looks like:
public class PdfFromHtmlResult : ViewResult {
public override void ExecuteResult(ControllerContext context) {
if (context == null) {
throw new ArgumentNullException("context");
}
if (string.IsNullOrEmpty(this.ViewName)) {
this.ViewName = context.RouteData.GetRequiredString("action");
}
if (this.View == null) {
this.View = this.FindView(context).View;
}
// First get the html from the Html view
using (var writer = new StringWriter()) {
var vwContext = new ViewContext(context, this.View, this.ViewData, this.TempData, writer);
this.View.Render(vwContext, writer);
// Convert to pdf
var response = context.HttpContext.Response;
using (var pdfStream = new MemoryStream()) {
var pdfDoc = new Document();
var pdfWriter = PdfWriter.GetInstance(pdfDoc, pdfStream);
pdfDoc.Open();
using (var htmlRdr = new StringReader(writer.ToString())) {
var parsed = iTextSharp.text.html.simpleparser.HTMLWorker.ParseToList(htmlRdr, null);
foreach (var parsedElement in parsed) {
pdfDoc.Add(parsedElement);
}
}
pdfDoc.Close();
response.ContentType = "application/pdf";
response.AddHeader("Content-Disposition", this.ViewName + ".pdf");
byte[] pdfBytes = pdfStream.ToArray();
response.OutputStream.Write(pdfBytes, 0, pdfBytes.Length);
}
}
}
}
With the correct extension methods (see BitBucket), etc, the code in my controller is something like:
public ActionResult MyPdf(int id) {
var myModel = findDataWithID(id);
// this assumes there is a MyPdf.cshtml/MyPdf.aspx as the view
return this.PdfFromHtml(myModel);
}
Note: Your method does not work, because you will retrieve the Html on the server, thereby you loose all cookies (=session information) that are stored on the client.
This code is supposed to download a file using mvc3 controller
public FilePathResult GetFileFromDisk(String file)
{
String path = AppDomain.CurrentDomain.BaseDirectory + "AppData/";
String contentType = "text/plain";
return File(path+file, contentType, file);
}
View part :
#Html.ActionLink("Download", "GetFileFromDisk","Upload", new { file = "textfile" },null);
But when i click the link I am getting this error
Could not find a part of the path 'D:\Project\FileUploadDownload\FileUploadDownload\AppData\textfile'.
[DirectoryNotFoundException: Could not find a part of the path 'D:\Project\FileUploadDownload\FileUploadDownload\AppData\textfile'.]
Why the foldername is repeating in the file path? Please offer a solution...
Try like this:
public ActionResult GetFileFromDisk(string file)
{
var appData = Server.MapPath("~/App_Data");
var path = Path.Combine(appData, file);
path = Path.GetFullPath(path);
if (!path.StartsWith(appData))
{
// Ensure that we are serving file only inside the App_Data folder
// and block requests outside like "../web.config"
throw new HttpException(403, "Forbidden");
}
if (!System.IO.File.Exists(path))
{
return HttpNotFound();
}
var contentType = "text/plain";
return File(path, contentType, Path.GetFileName(path));
}