I have a View that displays a list of images and i am now trying to get it to display the images as thumbnails. Well, i'm pretty sure i got most of it right using VirtualPath's from a custom ActionResult although i can't seem to figure out what it is making the VirtualPath url?? BTW, i'm using XML to store the data from the images instead of SQL. Here is my code:
Code from my custom ActionResult:
public class ThumbnailResult : ActionResult
{
public ThumbnailResult(string virtualPath)
{
this.VirtualPath = virtualPath;
}
public string VirtualPath { get; set; }
public override void ExecuteResult(ControllerContext context)
{
context.HttpContext.Response.ContentType = "image/bmp";
string fullFileName =
context.HttpContext.Server.MapPath("~/Galleries/WhereConfusionMeetsConcrete/" + VirtualPath);
using (System.Drawing.Image photoImg =
System.Drawing.Image.FromFile(fullFileName))
{
using (System.Drawing.Image thumbPhoto =
photoImg.GetThumbnailImage(100, 100, null, new System.IntPtr()))
{
using (System.IO.MemoryStream ms = new System.IO.MemoryStream())
{
thumbPhoto.Save(ms, System.Drawing.Imaging.ImageFormat.Jpeg);
context.HttpContext.Response.BinaryWrite(ms.ToArray());
context.HttpContext.Response.End();
}
}
}
}
}
Code for my Controller:
public ActionResult Thumbnail(string id)
{
return new ThumbnailResult(id);
}
Code for my View:
<% foreach (var image in ViewData.Model) { %>
<img src="../Galleries/TestGallery1/thumbnail/<%= image.Path %>" alt="<%= image.Caption %>" />
<br /><br /><%= image.Caption %><br /><br /><br />
<% } %>
Any help would be greatly appreciated!! Let me know of any questions you have as well. :) Thanks!
From what I can see you are using the VirtualPath string member in the ThumbnailResult custom action to identify the last portion of the image url. So for example if your site is located at c:\wwwroot\Galleries\WhereConfusionMeetsConcrete and the image files are located inside this folder like image1.bmp, image2.bmp, ... you could only pass the image filename to the custom action result constructor which is called in the controller action and passed the id parameter. So in order to show a thumbnail for image1.bmp in your view you could do this:
<img src="<%= Url.RouteUrl(new { controller = "home", action = "Thumbnail", id = "image1.bmp" }) %>" alt="" />
Of course this assumes that you have a default route like this:
routes.MapRoute(
"Default",
"{controller}/{action}/{id}",
new { controller = "Home", action = "Index", id = UrlParameter.Optional }
);
Related
Im trying to create an actionlink to download a file. I get the values of noticiaId and filename in the view but not in the controller.
There's something wrong with the actionlink HTML helper that Im missing.
If I do it this way:
#Html.ActionLink("Download", "DownloadAnexo", "NoticiasController", new { noticiaid = Model.ID, filename = f.File }, null)
I get HTTP 404 with this URL: localhost:port/NoticiasController/DownloadAnexo?noticiaid=55&filename=file.png
This looks correct to me but still Im getting 404 errors saying that the route was not found.
Partial View:
#model Web.Models.Noticias.NoticiaVM
<div class="col">
<label>Anexos:</label>
<table>
#if (Model.Anexos != null)
{
foreach (var f in Model.Anexos)
{
<tr>
<td>#f.File</td>
<td>
#Html.ActionLink("Download", "DownloadAnexo", "NoticiasController", new { noticiaid = Model.ID, filename = f.File }, null)
</td>
</tr>
}
}
</table>
</div>
Controller Action:
public ActionResult DownloadAnexo(int? noticiaid, string filename)
{
if(noticiaid != null && !String.IsNullOrEmpty(filename))
{
string fullPath = ConfigurationManager.AppSettings["NoticiasFiles"] + "/N_" + noticiaid + "/Anexos/";
byte[] fileBytes = System.IO.File.ReadAllBytes(fullPath);
return File(fileBytes, System.Net.Mime.MediaTypeNames.Application.Octet, filename);
}
else
return Content("");
}
I've also tried this:
<a href="#Url.Action("DownloadAnexo", "NoticiasController",
new { noticiaId = Model.ID, filename = f.File })">
Download
</a>
But i got the same result.
I'm don't have much experience with partialviews, so I'm wondering if just because im sending data from a partial directly to the controller that might not be possible or something. IDK.
Please Help.
you have a typo, NoticiasController should be Noticias
#Html.ActionLink("Download", "DownloadAnexo", "Noticias", new { noticiaid = Model.ID, filename = f.File }, null)
and fix action too
public ActionResult DownloadAnexo([FromQuery] int? noticiaid, [FromQuery]string filename)
I have an iframe which uses a Url.Action to open a PDF from an action controller. Is it possible to open this PDF on a certain page? Determined by a value in the model e.g. #Model.FilePage
iframe:
<iframe width="700" height="1600" src="#Url.Action("OpenPDF", new { id = 8 })"></iframe>
controller action:
public ActionResult OpenPDF(int? id)
{
CompletedCamp completedCamp = db.CompletedCamps.Find(id);
string filepath = Server.MapPath(Path.Combine("~/Surveys/" + completedCamp.SurveyName));
return File(filepath, "application/pdf");
}
To open on specific page, add #page=[page number] to the end of src
<iframe width="700" height="1600" src="#Url.Action("OpenPDF", new { id = 8 })#page=4"></iframe>
if page number should be from the model, do
public ActionResult Index()
{
MyViewModel m = new MyViewModel() { FilePage = 4 };
return View(m);
}
...
#model MVC.MyViewModel
<iframe width="700" height="1600" src="#Url.Action("OpenPDF", new { id = 8 })#page=#Model.FilePage"></iframe>
I'am new in ASP.net... I tried to Display an Image from an MySql DataBase but nothing shows ...
In my Product Class I have a List of a Pictures :
public partial class product
{
public product()
{
this.orderitems = new List<orderitem>();
this.pictures = new List<picture>();
this.productitemsuppliers = new List<productitemsupplier>();
this.recommendations = new List<recommendation>();
this.reviews = new List<review>();
this.productitems = new List<productitem>();
}
I habve this Method in my ProductController:
static IDatabaseFactory dbFact = new DatabaseFactory();
IUnitOfWork utOfW = new UnitOfWork(dbFact);
public FileContentResult imageGenerate(int id)
{
byte[] image = utOfW.ProductRepository.GetById(id).pictures.ElementAt(0).picture1;
// Another way to get the Byte Array from the Database...
// byte[] image = utOfW.PictureRepository.GetMany(p=>p.product.idProduct==id).ElementAt(0).picture1;
if (image != null) {
return new FileContentResult(image, "image/jpg");
}
return null;
}
and in my View :
#foreach (var item in Model) {
....
<td>
<img id="image" src='#Url.Action("imageGenerate", "ProductController", new { id = item.idProduct})'/>
</td>
}
It seems to be ok but the reseult isn't...
Thanks for your Help
First, check if you can see the file using just simple web request, e.g. http://youraddress/Product/imageGenerate/5. If you can't, then it is an issue with generating of an image.
If you can see the image, then it is likely that you are using ProductController' in your view. You only need to specify name of the controller without extensionController`. So your image code should look like the following:
<img id="image" src='#Url.Action("imageGenerate", "Product", new { id = item.idProduct})'/>
#dotnetom
First thank you for your quick answer ...
I changed the call to :
<img id="image" src='#Url.Action("imageGenerate", "Product", new { id = item.idProduct})'/>
but now I have an another Problem :
But I am quite sure that this Method works I have tested it in the Index Method of the ProductController
public ActionResult Index()
{
var products = db.products.Include(p => p.category).Include(p => p.promotion).Include(p => p.user);
ViewBag.Count = utOfW.ProductRepository.GetById(1).pictures.Count(); // the result is 3 and it is true
return View(products.ToList());
}
This is my part of View:
<img src="#{Html.RenderAction("GetUserProfileImage", "Home", new { area = "" });}" alt="" />
And My Controller:
public ActionResult GetUserProfileImage() {
string defaultresult = "http://MyProject.dev/Content/img/sample_user.png";
if (Member.LogIn()) {
DBFile file = GetMemberPicFromDB();
return File(file.Content, file.ContentType);
} else {
return Content(defaultresult);
}
}
So when I Get File from DB every thing is OK, but when I return URL(by return Content) there is some bad result in rendered html, something like this:
<imghttp: myproject.dev="" content="" img="" sample_user.png="" src="" alt="">
<div>
some content from outside of img tag added here
</div>
</imghttp:>
Also I change the View to:
<img src="http://myproject.dev/Content/img/sample_user.png" alt="" />
And every thing is OK,
So where is the problem? it seems return Content can not return simple string to src attribute, So what is your suggestion for return simple string?
if that not possible
I think to get File by URL(http://myproject.dev/Content/img/sample_user.png) and return File() Like when returned from DB, but how can I get the file in controller by this URl(http://myproject.dev/Content/img/sample_user.png) ?
and any other suggestion if you have?
You should return a file from your controller action in both cases and reference this action in your image, like this:
<img src="#Url.Action("GetUserProfileImage", "Home", new { area = "" })" alt="" />
and then in your controller action return a File result in both cases:
public ActionResult GetUserProfileImage()
{
if (Member.LogIn())
{
DBFile file = GetMemberPicFromDB();
return File(file.Content, file.ContentType);
}
else
{
string image = Server.MapPath("~/content/img/sample_user.png");
return File(image, "image/png");
}
}
I am trying to implement a simple captcha system and I wish to output an image without using its original name.
For example I would like to ouput the image file 8.gif to the page with the name captcha1.gif
I have read the various posts but I am looking for the simplest solution.
Here's what I have so far...
<% Html.RenderAction("OuputCaptchaImage", "Home", new { imageName = "1" }); %>
public ActionResult OuputCaptchaImage(string imageName)
{
var dir = Server.MapPath("images/");
var path = Path.Combine(dir, imageName + ".gif"); // Like to change name here
return base.File(path, "image/gif");
}
and what I would like to render to the page
<img src="image/captcha1.gif" />
The following mark-up will output the image correctly. However you still have the problem of the file name being referenced in the url.
<img src="<%= Url.Action("OuputCaptchaImage", "Home", new { imageName = "1" })%>" />
Which would output the following HTML:
<img src="/Home/OuputCaptchaImage?imageName=1" />
You could specify some other value as a parameter such as an enumeration rather than the image name, and then modify your logic to return the correct file.
However (AFAIK) to output an image with a file name which does not exist would require an Httphandler to intercept the request and write out the image you require to the response stream.
Edit
Here is an example of using an HttpHandler to intercept the incoming request for "captcha1.gif" and streaming a different image to the response:
Mark-up
<img src="Images/captcha1.gif" />
HttpHandler
public class OuputCaptchaImageHandler : IHttpHandler
{
public bool IsReusable
{
get
{
return false;
}
}
public void ProcessRequest(HttpContext context)
{
string imagePath =
context.Server.MapPath(#"~\Images\1.gif");
Bitmap bitmap = new Bitmap(imagePath);
context.Response.ContentType = "image/gif";
bitmap.Save(context.Response.OutputStream, ImageFormat.Gif);
bitmap.Dispose();
}
}
Web.Config
<httpHandlers>
<add verb="*" path="Images/captcha1.gif" type="FullyQualifiedNameSpace.OuputCaptchaImageHandler, RootNamespace" validate="false"></add>
</httpHandlers>
Global.asax.cs
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("Images/captcha1.gif/{*pathInfo}");
....
Hope this helps.