download pdf files stored in database in mvc3 - asp.net-mvc-3

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");
}

Related

how to save byte[] image in custom folder in webapi?

i have one model contain image ,i send model from angularjs and get model in webapi ,my method in web api
public IHttpActionResult Post([FromBody]Game model)
{
Image img = LoadImage(model.Image);
Game game = model;
_repository.Add<Game>(game);
return Ok();
}
public Image LoadImage(string imageName)
{
string[] str = imageName.Split(',');
byte[] bytes = Convert.FromBase64String(str[1]);
Image image;
using (MemoryStream ms = new MemoryStream(bytes))
{
image = Image.FromStream(ms);
}
return image;
}
but this code just return base64 to image,i want save jpg on custom folder in project
this code solve your problem
public IHttpActionResult Post([FromBody]Game model)
{
var image = SaveImage(model.Image, Guid.NewGuid().ToString());
model.Image = image; // set image name in model
_repository.Add<Game>(model);
return Ok();
}
public string SaveImage(string ImgStr, string ImgName)
{
String path = HttpContext.Current.Server.MapPath("~/images/Games"); //Path
//Check if directory exist
if (!System.IO.Directory.Exists(path))
{
System.IO.Directory.CreateDirectory(path); //Create directory if it doesn't exist
}
string imageName = ImgName + ".jpg";
//set the image path
string imgPath = Path.Combine(path, imageName);
string[] str = ImgStr.Split(',');
byte[] bytes = Convert.FromBase64String(str[1]);
File.WriteAllBytes(imgPath, bytes);
return imageName;
}

I can not get data in my excel export file in MVC application?

Everything is setup well (call method, .xsd file, rdlc file, when i do debugging I can see data in my model, I can download the excel file, but it is still remining empty?! Wher did I'm wrong in my code? Any clue?
My ActionResult in Controller:
[HttpGet]
public ActionResult Export_StudentStatus()
{
List<pr_ReportDataGenerate_AllGeneralOverview_Result> model = Context.pr_ReportDataGenerate_AllGeneralOverview().Where(p => p.rdTypeID == 2).ToList();
ReportViewer viewer = new ReportViewer();
try
{
Warning[] warnings;
string[] streamIds;
string mimeType = string.Empty, encoding = string.Empty, extension = string.Empty;
viewer.ProcessingMode = ProcessingMode.Local;
//viewer.LocalReport.EnableExternalImages = true;
viewer.LocalReport.ReportPath = Server.MapPath("~/RDLC/GeneralOverviewStudentStatus.rdlc");
viewer.LocalReport.DataSources.Add(new ReportDataSource("dsGeneralOverviewAnnualAwards", model));//ova e DS vo reportot
viewer.LocalReport.EnableHyperlinks = true;
byte[] bytes = viewer.LocalReport.Render("Excel", null, out mimeType, out encoding, out extension, out streamIds, out warnings);
Response.Clear();
Response.ContentType = mimeType;
Response.AddHeader("content-disposition", "attachment; filename=GeneralOverviewStudentStatus.xls");
Response.BinaryWrite(bytes);
Response.End();
return null;
}
finally
{
if (viewer != null)
{
viewer.Dispose();
viewer = null;
}
}
}

MVC 6 HttpPostedFileBase?

I am attempting to upload an image using MVC 6; however, I am not able to find the class HttpPostedFileBase. I have checked the GitHub and did not have any luck. Does anyone know the correct way to upload a file in MVC6?
MVC 6 used another mechanism to upload files. You can get more examples on GitHub or other sources. Just use IFormFile as a parameter of your action or a collection of files or IFormFileCollection if you want upload few files in the same time:
public async Task<IActionResult> UploadSingle(IFormFile file)
{
FileDetails fileDetails;
using (var reader = new StreamReader(file.OpenReadStream()))
{
var fileContent = reader.ReadToEnd();
var parsedContentDisposition = ContentDispositionHeaderValue.Parse(file.ContentDisposition);
var fileName = parsedContentDisposition.FileName;
}
...
}
[HttpPost]
public async Task<IActionResult> UploadMultiple(ICollection<IFormFile> files)
{
var uploads = Path.Combine(_environment.WebRootPath,"uploads");
foreach(var file in files)
{
if(file.Length > 0)
{
var fileName = ContentDispositionHeaderValue.Parse(file.ContentDisposition).FileName.Trim('"');
await file.SaveAsAsync(Path.Combine(uploads,fileName));
}
...
}
}
You can see current contract of IFormFile in asp.net sources. See also ContentDispositionHeaderValue for additional file info.
There is no HttpPostedFileBase in MVC6. You can use IFormFile instead.
Example: https://github.com/aspnet/Mvc/blob/dev/test/WebSites/ModelBindingWebSite/Controllers/FileUploadController.cs
Snippet from the above link:
public FileDetails UploadSingle(IFormFile file)
{
FileDetails fileDetails;
using (var reader = new StreamReader(file.OpenReadStream()))
{
var fileContent = reader.ReadToEnd();
var parsedContentDisposition = ContentDispositionHeaderValue.Parse(file.ContentDisposition);
fileDetails = new FileDetails
{
Filename = parsedContentDisposition.FileName,
Content = fileContent
};
}
return fileDetails;
}
I was searching around for quite a while trying to piece this together in .net core and ended up with the below. The Base64 conversion will be next to be done so that the retrieval and display is a little easier. I have used IFormFileCollection to be able to do multiple files.
[HttpPost]
public async Task<IActionResult> Create(IFormFileCollection files)
{
Models.File fileIn = new Models.File();
if(model != null && files != null)
{
foreach (var file in files)
{
if (file.Length > 0)
{
var fileName = ContentDispositionHeaderValue.Parse(file.ContentDisposition).FileName.Trim('"');
byte[] fileBytes = null;
using (var fileStream = file.OpenReadStream())
using (var ms = new MemoryStream())
{
fileStream.CopyTo(ms);
fileBytes = ms.ToArray();
//string s = Convert.ToBase64String(fileBytes);
// act on the Base64 data
}
fileIn.Filename = fileName;
fileIn.FileLength = Convert.ToInt32(file.Length);
fileIn.FileType = file.ContentType;
fileIn.FileTypeId = model.FileTypeId;
fileIn.FileData = fileBytes;
_context.Add(fileIn);
await _context.SaveChangesAsync();
}
}
}
return View();
}
EDIT
And below is return of files to a list and then download.
public JsonResult GetAllFiles()
{
var files = _context.File
.Include(a => a.FileCategory)
.Select(a => new
{
id = a.Id.ToString(),
fileName = a.Filename,
fileData = a.FileData,
fileType = a.FileType,
friendlyName = a.FriendlyName,
fileCategory = a.FileCategory.Name.ToLower()
}).ToList();
return Json(files);
}
public FileStreamResult DownloadFileById(int id)
{
// Fetching file encoded code from database.
var file = _context.File.SingleOrDefault(f => f.Id == id);
var fileData = file.FileData;
var fileName = file.Filename;
// Converting to code to byte array
byte[] bytes = Convert.FromBase64String(fileData);
// Converting byte array to memory stream.
MemoryStream stream = new MemoryStream(bytes);
// Create final file stream result.
FileStreamResult fileStream = new FileStreamResult(stream, "*/*");
// File name with file extension.
fileStream.FileDownloadName = fileName;
return fileStream;
}

How to Generate pdf of details view in mvc 3

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();
}
}

Convert PartialView Html to String for ITextSharp HtmlParser

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.

Resources