Mvc 3 Image Upload Gallery - asp.net-mvc-3

I have implemented a file upload for images using ASP.NET Mvc 3 and the Microsoft.Web.Helpers NuGet package. The implementation is quit simple as it allows you to browse for a file and upload it to a specified directory.
Here is what I have for my image upload solution using ASP.NET MVC 3 and the Microsoft.Web.Helpers NuGet plugin.
Now the ViewModel code
namespace MvcImageUpload.Models {
public class ImageUploadViewModel {
[UIHint("UploadedImage")]
public string ImageUrl { get; set; }
public string ImageAltText { get; set; }
}
}
Now for the controller I've simply dropped this into the Home controller, since this is just a mock project to get it working. I just added an ActionResult which takes an ImageUploadViewModel as a parameter.
public ActionResult Upload(ImageUploadViewModel model) {
var image = WebImage.GetImageFromRequest();
if (image != null) {
if (image.Width > 500) {
image.Resize(500, ((500 * image.Height) / image.Width));
}
var filename = Path.GetFileName(image.FileName);
image.Save(Path.Combine("../Uploads/Images", filename));
filename = Path.Combine("~/Uploads/Images", filename);
model.ImageUrl = Url.Content(filename);
model.ImageAltText = image.FileName.Substring(0, image.FileName.Length - 4);
}
return View("Index", model);
}
My view for the uploading of images is simple, it has an Html.BeginForm, which handles the Post form method and has the encoding type set to be "multipart/form-data".
Then using The Microsoft.Web.Helpers.FileUpload helper, I request an image from the HTTP post and then display it using a custom DisplayFor template, called ImageViewer.
#model MvcImageUpload.Models.ImageUploadViewModel
#using Microsoft.Web.Helpers;
#{
ViewBag.Title = "Index";
}
<h2>Image Uploader</h2>
#using (Html.BeginForm("Upload", "Home", FormMethod.Post,
new { #encType = "multipart/form-data" })) {
#FileUpload.GetHtml(initialNumberOfFiles: 1, allowMoreFilesToBeAdded: false,
includeFormTag: false, addText: "Add Files", uploadText: "Upload File") <br />
<input type="submit" name="submit"
value="Upload Image" text="Upload Images"
style="font-size: .9em;" />
#Html.DisplayFor(x => x, "ImageViewer")<br />
}
Here is what the custom DisplayTemplate looks like
#model MvcImageUpload.Models.ImageUploadViewModel
#if (Model != null) {
<h4 style="color:Green;">Upload Success!</h4>
<p>
Alt Text has been set to <strong>#Model.ImageAltText</strong>
</p>
<img style="padding: 20px;"
src="#(String.IsNullOrEmpty(Model.ImageUrl) ? "" : Model.ImageUrl)"
id="uploadedImage" alt="#Model.ImageAltText"/>
}
This all works and the image gets successfully uploaded to the /Uploads/Images/FileName.extension on the form post.
My question
How can I now have another view to display all the images in that directory, paged and be able to select and delete and image, from the view and the directory?
Also I know the Microsoft.Web.Helpers.FileUpload, supports uploading of multiple files, but I can't find how to implement this with my current solution. Any help would be greatly appriceated.

After you click the Upload Image button, the system should call method which uses Request to get the file.
[HttpPost]
public ActionResult Upload()
{
if(Request.Files != null && Request.Files.Count > 0)
{
for (int i = 0; i < request.Files.Count; i++)
{
var postFile = request.Files[i];
if (postFile != null && postFile.ContentLength > 0)
{
if (postFile.ContentLength < GetMaxRequestLength()) //10MB
{
var file = new ContractAttachment
{
Name = Path.GetFileName(postFile.FileName),
ContentType = postFile.ContentType,
FileLength = postFile.ContentLength,
FileData = GetStreamBuffer(postFile)
};
files.Add(file);
}
}
}
}
}
Hope this help.

what you are asking about looks rather implementation to me then any query....
to Display:
Fetch all images from your Uploads/Images directory through DirectoryInfo... you can search a directory based on some extension and then it will give you a result set which you can iterate.....
Create a view that will display all records as Image links and in controller fetch the resultset to that View.... Bind those records as you want them to display in your VIEW...
System.IO.DirectoryInfo info = new System.IO.DirectoryInfo("your directory path");
var filesinfo= info.GetFiles("*.jpg", System.IO.SearchOption.AllDirectories);
var filenum= filesinfo.GetEnumerator();
while (filenum.MoveNext())
{
//populate some entity like in your case you have ImageUploadViewModel
}
and you can implement you delete logic using Ajax or through post back depends how you want it....
Asp.net MVC Views following this tutorial and it will let you go through this....
but again what you are asking is more like implementation Code not any issue....

The approach I've followed previously, is to persist the file information in a database(or whatever is appropriate). e.g. path, filename, content-type, filesize.
This gives you the most flexibility when editing (alt text, title, description, relation to other objects).
Downloading/Viewing the files can then be handled based on path convention, by creating a ViewImage controller which just gets an image id as parameter.
You can then build a url from the path to the file and you only need to set the content-type.
IIS then does the rest.

Related

How to create subfolder based on user name in .NET Core on image upload?

I am trying to create a sub folder inside an already created folder every time an user registers so that every video/image a user whats to upload to go in the folder of that specific user.My problem is that i can't get it to work for some reason.I have an auto generated controller that adds the user and a method that uploads an image to the server.
[HttpPost]
public async Task<ActionResult<User>> PostUser(User user)
{
_context.User.Add(user);
if (string.IsNullOrWhiteSpace(_env.WebRootPath))
{
_env.WebRootPath = Path.Combine(Directory.GetCurrentDirectory(), "wwwroot");
}
if(user!=null)
{
var users = Path.Combine(_env.WebRootPath,"uploads",user.Name);
Directory.CreateDirectory(users);
}
await _context.SaveChangesAsync();
return CreatedAtAction("GetUser", new { id = user.IdUser }, user);
}
Here i try to create a sub folder inside "uploads" folder as the other is already created when the user uploads an image for the first time.The problem is that no matter what I do,it doesn't get created.On top of that I would like to save the image directly to the user folder.For now i can save it only in "uploads" folder.This is my method for the image upload:
[HttpPost]
public async Task PostImage(IFormFile file)
{
if (string.IsNullOrWhiteSpace(_env.WebRootPath))
{
_env.WebRootPath = Path.Combine(Directory.GetCurrentDirectory(), "wwwroot");
}
var uploads = Path.Combine(_env.WebRootPath, "uploads");
if (!Directory.Exists(uploads)) Directory.CreateDirectory(uploads);
if (file.Length > 0)
{
using (var fileStream = new FileStream(Path.Combine(uploads, file.FileName), FileMode.Create))
{
await file.CopyToAsync(fileStream);
}
}
}
I have also tried to declare a User property inside the PostImage() method but the user is null in the moment I post the image as the registration is made at the same time with the image upload so automatically it will not work.I also tried to play around with the client side and check if the user has been saved and then to proceed with uploading the file,but without any luck.Can someone please point me into the right direction?
Obviously, when PostImage stores images, your path only reaches uploads folder, not subfolders, so the images will only be stored under the uploads folder.
If you want to store the images in the corresponding uploads/username folder, you also need to obtain the user information corresponding to the current uploaded image.
As you said, this is a registration page, so the user's information and images can be passed to the action at the same time. You don't need to use the two post methods, just merge them.
View:
#model User
#{
ViewData["Title"] = "Index";
Layout = "~/Views/Shared/_Layout.cshtml";
}
<h1>Index</h1>
<form method="post" asp-action="PostUserAndImage" enctype="multipart/form-data">
<input id="Text1" type="text" asp-for="IdUser" />
<input id="Text1" type="text" asp-for="Name" />
<input id="File1" type="file" name="file" />
<input id="Submit1" type="submit" value="submit" />
</form>
Action:
[HttpPost]
public async Task<ActionResult<User>> PostUserAndImage(User user, IFormFile file)
{
if (string.IsNullOrWhiteSpace(_env.WebRootPath))
{
_env.WebRootPath = Path.Combine(Directory.GetCurrentDirectory(), "wwwroot");
}
if (user != null)
{
_context.User.Add(user);
var users = Path.Combine(_env.WebRootPath, "uploads", user.Name);
if (!Directory.Exists(users)) Directory.CreateDirectory(users);
if (file.Length > 0)
{
using (var fileStream = new FileStream(Path.Combine(users, file.FileName), FileMode.Create))
{
await file.CopyToAsync(fileStream);
}
}
await _context.SaveChangesAsync();
}
return CreatedAtAction("GetUser", new { id = user.IdUser }, user);
}
Here is the test result:

Kendo UI ListView Template in MVC4

I am trying to get image files from the database and bind it to a KendoUI ListView. The problem is that it is not showing images at all.
This is what I have done:
View
<script type="text/x-kendo-tmpl" id="template">
<div class="product">
<img src="#Url.Content("#:PhotoID# + #:MIMEType#")" />
</div>
</script>
<div id="imageListView2" class="demo-section">
#(Html.Kendo().ListView<WorcesterMarble.ViewModels.PhotosViewModel>()
.Name("listView")
.TagName("div")
.ClientTemplateId("template")
.DataSource(dataSource =>
{
dataSource.Read(read => read.Action("GetImages", "StockReceiptsGrid").Data("passStockIDToListView"));
dataSource.PageSize(1);
})
.Pageable()
.Selectable(selectable => selectable.Mode(ListViewSelectionMode.Multiple))
//.Events(events => events.Change("onChange").DataBound("onDataBound"))
)
</div>
Controller
public JsonResult GetImages([DataSourceRequest] DataSourceRequest request, int stockReceiptID)
{
var photos = _stockPhotosRepository.GetStocReceiptkPhotos(stockReceiptID).ToList();
var photosList = new List<PhotosViewModel>();
//var photosList = new List<FileContentResult>();
if (photos.Count != 0)
{
foreach (var stockPhoto in photos)
{
var photoVm = new PhotosViewModel();
photoVm.PhotoID = stockPhoto.PhotoID;
photoVm.Image = stockPhoto.ImageData;
photoVm.MIMEType = stockPhoto.MIMEType;
// FileContentResult file = File(stockPhoto.ImageData, stockPhoto.MIMEType);
photosList.Add(photoVm);
}
return Json(photosList.ToList(), JsonRequestBehavior.AllowGet);
}
else
{
return null;
//FilePathResult file = this.File("/Content/Images/80.jpeg", "image/jpeg");
//return file;
}
return null;
}
Photo View Model:
public class PhotosViewModel
{
public int PhotoID { get; set; }
public byte[] Image { get; set; }
public string MIMEType { get; set; }
public int StockReceiptID { get; set; }
}
I am not sure if the problem is caused by the image url setting in the template. as you see it is not actually a url because the image is not saved anywhere except from the database. this is a screenshot of how the listview looks like; simply blank even though there must 15 images displayed!
Please let me know any clues or solutions to this problem.
I know this is a bit older, but what you need to do is change the line return Json(photosList.ToList(), JsonRequestBehavior.AllowGet); to the following:
return Json(photosList.ToDataSourceResult(request),
JsonRequestBehavior.AllowGet);
If the method ToDataSourceResult is not recognized, you have to add
using Kendo.Mvc.Extensions;
on top of your document.
It looks like you're missing a return in your controller (just before the end of your if)
return Json(photosList.ToList(), JsonRequestBehavior.AllowGet);
EDIT
Also, I noticed this:
<img src="#Url.Content("#:PhotoID# + #:MIMEType#")" />
Shouldn't that be:
<img src="#Url.Content("#:ImageData#")" />
or something similar?
It might be to late to answer, but your issue is that the json data being sent back to your view is to large so your images are not showing, rather save your images to a file and then render your images via a URL.

Unable to read View Bag value from controller to view

I have created a view bag in controller's post back event which stores the image path.
Then,i used this view bag value in image src attribute.But image is not displayed.
Model:
public class FileManagement
{
public string FileName { get; set; }
public string Path { get; set; }
}
Code for uploading image
[HttpPost]
public ActionResult UploadPic(FileManagement fmanage, HttpPostedFileBase file)
{
string email = User.Identity.Name;
if (file != null && file.ContentLength > 0)
{
var FileName = string.Format("{0}.{1}", Guid.NewGuid(), Path.GetFileName(file.FileName));
var path = Path.Combine(Server.MapPath("~/Content/Uploads"), FileName);
file.SaveAs(path);
using (var session = DocumentStore.OpenSession("RavenMemberShip"))
{
var query = from q in Session.Query<Registration>() where q.Email == email select q;
if (query.Count() > 0)
{
foreach (var updated in query)
{
updated.FileName = FileName;
updated.Path = path;
session.SaveChanges();
}
}
}
}
else ModelState.AddModelError("", "Remove the errors and try again");
return View();
}
Controller
[HttpGet]
public ActionResult DisplayPic()
{
ViewBag.Imagepath = "C:\\Users\\Wasfa\\Documents\\Visual Studio 2012\\Projects\\MvcMembership\\MvcMembership\\App_Data\\Uploads\\annonymous.jpg";
return View();
}
[HttpPost]
public ActionResult DisplayPic(FileManagement fm)
{
using (var session = DocumentStore.OpenSession("RavenMemberShip"))
{
string ipath;
// string UserName = User.Identity.Name;
string UserName = "wasfa_anjum#yahoo.com";
var getPath = from p in Session.Query<Registration>()
where p.Email == UserName
select p;
if (getPath.Count() > 0)
{
foreach (var imgpath in getPath)
{
ipath = imgpath.Path;
ViewBag.Imagepath = ipath;
}
}
}
return View();
}
View:
#using (Html.BeginForm())
{
<div>
<img src="#Url.Content(ViewBag.Imagepath)" width="200" height="200" />
</div>
<input type="submit" value="Display" />
}
In my opinion, your problem is not to do with ASP.NET MVC, but you are missing some HTML/Web basics.
You have to understand that when you want to access a resource (html file, image etc), you have to use the HTTP URI syntax. You cannot and should not use your Windows file system path syntax.
Using something like C:\\Users\\Wasfa\\Documents\\Visual Studio 2012\\Projects\\MvcMembership\\MvcMembership\\App_Data\\Uploads\\annonymous.jpg" in HTML is completely wrong. To understand it better, imagine when you have your ASP.NET MVC website up and running for its users to access, they will come to you web page and the HTML downloaded on their browser will be:
<img src="C:\Users\Wasfa\Documents\Visual Studio 2012\Projects\MvcMembership\MvcMembership\App_Data\Uploads\annonymous.jpg" />
Do you think that path will exist on their computers? No.
So, to instruct the <img /> tag to fetch the image from the server, you have to specify either a full HTTP URI, for example:
<img src="http://mywebsite.com/Content/Uploads/annonymous.jpg" />
or a relative HTTP URI (which is like a relative path from your web site's root folder):
<img src="~/Content/Uploads/annonymous.jpg" />
Another problem with your approach is that App_Data is a special folder and its contents are not accessible from the browser by default. So, as per ASP.NET MVC convention, you can create a Content folder in your project to hold your static images and other static content like style sheels, and then link to them.
Once you do that, no one stops you from providing the relative path for your default image as a ViewBag property.
ViewBag.Imagepath = "~/Content/Uploads/annonymous.jpg";
And then use it the way you want:
<img src="#Url.Content(ViewBag.Imagepath)" width="200" height="200" />
I also expect the paths you subsequently fetch from the database, also follow this scheme.
path for image must have forward slash (/),
more over this type of path might work only in your local system and not in your server.
Try using Server.MapPath to fetch your path
Using ViewBag for displaying image is a bad idea, consider using your model property to store the image path and use
<img src="#Url.Content(Model.ImagePath)" alt = "Image" />
EDIT :
Controller:
[HttpGet]
public ActionResult DisplayPic()
{
FileManagement fm = new FileManagement();
fm.Path = "Your image path";
return View(fm);
}
View :
`<img src="#Url.Content(Model.path)" alt = "Image" />`
didn't check the code, but this should work.
It looks like you only really need one result for getPath, this might clean your code up a bit
var imgPath= Session.Query<Registration>()
.FirstOrDefault(p => p.Email == UserName)
.Select(i => i.Path);
if (!string.IsNullOrEmpty(imgPath)
ViewBag.Imagepath = imgPath;
else
{
//no user found, handle error
}
Other than that your code looks fine, can you debug through your application and see what imgPath is equal to after your query is run?
In case, if the image to be displayed when export to excel from the web page.
Use the server path of the image, otherwise, the image would not be loaded from the assembly image folder.
Example:
config:
<add key="LogoPath" value="http:\\mysite\\images\\" />
code:
companyLogo = string.Format("{0}myLogo.png", System.Web.Configuration.WebConfigurationManager.AppSettings["LogoPath"]);
HTML:
<img src='" + #Url.Content(companyLogo) + "' />

What is a way to share a drop down inside a layout for use in all views?

I am becoming more familiar with MVC 3 and the RAZOR view engine. I have a question regarding layouts and shared controls on pages.
Let’s say I have a header section defined in my main layout. In that header is a dropdown I need to populate with project names. This dropdown will serve as a context for the entire site and is present on all pages. As an example, if the user selects “Project A” from the drop down, all of the views for the site will be based on “Project A”. Since this dropdown control is rather static and is used by the entire site, where is the best place to put the code to pull all the projects to display in the dropdown? In a Partial View? In a HTML helper? Another thought is, if a user selects a new value, they would be taken to a dashboard or similar page for that newly selected project. I am trying to figure out how to reuse this control on every page in the site without having to keep wiring it up in every possible controller.
You could use a child action along with the Html.Action helper. So you start by defining a view model:
public class ProjectViewModel
{
[DisplayName("Project name")]
public string ProjectId { get; set; }
public IEnumerable<SelectListItem> ProjectNames { get; set; }
}
then a controller:
public class ProjectsController: Controller
{
private readonly IProjectsRepository _repository;
public ProjectsController(IProjectsRepository repository)
{
_repository = repository;
}
public ActionResult Index(string projectId)
{
var projects = _repository.GetProjects();
var model = new ProjectViewModel
{
ProjectId = projectId,
ProjectNames = projects.Select(x => new SelectListItem
{
Value = x.Id,
Text = x.Name
})
};
return PartialView(model);
}
}
then the corresponding view (~/views/projects/index.cshtml):
#model ProjectViewModel
#Html.LabelFor(x => x.ProjectId)
#Html.DropDownListFor(
x => x.ProjectId,
Model.ProjectNames,
new {
id = "projects",
data_url = Url.Action("SomeAction", "SomeController")
}
)
Now all that's left is to render this widget inside the _Layout.cshtml:
#Html.Action("Index", "Products", new { projectid = Request["projectId"] })
And now we could put some javascript so that when the user decides to change the selection he is redirected to some other action:
$(function() {
$('#projects').change(function() {
var url = $(this).data('url');
var projectId = encodeURIComponent($(this).val());
window.location.href = url + '?projectid=' + projectId;
});
});
Another possibility is to put the dropdown inside an HTML form:
#model ProjectViewModel
#using (Html.BeginForm("SomeAction", "SomeController", FormMethod.Get))
{
#Html.LabelFor(x => x.ProjectId)
#Html.DropDownListFor(
x => x.ProjectId,
Model.ProjectNames,
new {
id = "projects",
}
)
}
so that inside the javascript we don't have to worry about building urls when the selection changes and simply trigger the containing form submission:
$(function() {
$('#projects').change(function() {
$(this).closest('form').submit();
});
});
We just did a similiar thing on a project.
First, you can't really put it in a section because you have to put that section on every view, you could put it in a partial but you would still have to call it from every view.
Second, you can't really put it in the Layout page because the layout page isn't passed any kind of model. So I created an html helper and referenced that in the layout page. There are lots of tutorials on creating html helpers so I won't put the code here. But essentially in your html helper you can make a database call to get all of your projects. Then you can create a select list using string builder in the html helper and return that to the layout page. We then used jquery to add an on change event to the select list. When the select list changed it loaded a new page. So for example, in your select list the value of each item could be the project id, then on change it redirects them to a page like /Projects/View?id=234 where 234 is your project id.
So things to research. 1. Creating HTML Helpers 2. JQUERY change event.
That should get you in the right direction. Let me know if you need any other help and I can post some code.

ASP.NET MVC3 - Pagination Only (No WebGrid to be Displayed)

I'm seeking to display my images with a short title in a flow from left to right as opposed to the gridview that is a sequential layout. I desire to use the pagination that the webgrid provides so as not to recreate the wheel, as it were.
I've reviewed Leek's blog post (http://msdn.microsoft.com/en-gb/magazine/hh288075.aspx) and Broer's (http://blog.bekijkhet.com/2011/03/mvc3-webgrid-html-helper-paging.html) to ensure I have a solid introduction to the use of the webgrid but I'm falling short on how to apply the pagination without using the traditional layout of the webgrid.
I am using the Razor layouts.
Ideas or thoughts?
My controller is currently:
public ActionResult Index(string cid)
{
Catalog item = new Catalog();
item.objConnection.Open();
OdbcDataReader reader = item.getCatalogItems(cid, 3);
List<Catalog> listItems = new List<Catalog>();
while (reader.Read())
{
Catalog i = new Catalog();
i.kitName = reader.GetValue(1).ToString();
i.catalogID = reader.GetValue(0).ToString();
ViewBag.CatalogName = reader.GetValue(0).ToString(); //TODO: change this to name once in place
listItems.Add(i);
}
ViewBag.ItemsPerCatagory = listItems.Count;
reader.Close();
item.objConnection.Close();
return View(listItems);
}
My View:
#model IEnumerable<MvcApplication1.Models.Catalog>
#{
ViewBag.Title = ViewBag.CatalogName;
Layout = "~/Views/Shared/_Layout.cshtml";
}
<h2>#ViewBag.CatalogName (#ViewBag.ItemsPerCatagory) Items Available</h2>
<p>
Category will have a brief description here for seo purposes.
</p>
<p>
#foreach (var catalog in Model)
{
string imageUrl = "http://web3.naeir.org/images/Specials/" + #catalog.kitName + ".JPG";
<img src=#imageUrl height="150px" width="150px" /> #Html.ActionLink(#catalog.kitName, "Details", "Product", new { cid = #catalog.catalogID, itemid = #catalog.kitName }, null)
}
</p>
Upon much hacking at my code I found that a simple option exist and my solution was to use MVCPager MVC Pager Website
I was able to simply download it via VS Web Developer Express Package Manager NuGet, read the documentation and implemented the code. Pretty straight forward.

Resources