Click here to Skip to main content
15,894,410 members
Please Sign up or sign in to vote.
1.00/5 (3 votes)
See more:
Hello everyone, I am trying to upload an image in asp.net mvc 5 and save it to a database, until now I have copied my file in a folder, and I'm trying to save that route to my database, this is my controller code...

C#
[HttpPost]
        public ActionResult Upload(HttpPostedFileBase file)
        {
            var model = new ImageModel();
            try
            {
                if (file.ContentLength > 0)
                {
                    var fileName = Path.GetFileName(file.FileName);
                    var path = Path.Combine(Server.MapPath("~/Content/Uploads"), fileName);
                    model.ImageServerPath = path;
                    file.SaveAs(path);
                    db.images.Add(model); //Database
                    db.SaveChanges();
                }
                ViewBag.Message = "Upload Successful";
                return RedirectToAction("Index");
            }
            catch (Exception e)
            {
                ViewBag.Message = "Upload Failed";
                return RedirectToAction("Upload");
            }
        }

In my view the only thing that I have is a file input, and a button, and this is my model code...
C#
public class ImageModel
   {
       [Key]
       public int Id { get; set; }
       public string ImageServerPath { get; set; }
   }

And know, my question is, How is the best way to do this?.

Besides, I need to show all the images in my index, but that doesn't work either, don't show nothing, only thumbnails from bootstrap with the alt text inside of it, how can I get the route of my uploaded files, and show the content of the image in that route in my index file?, here is my code...
HTML
@model IEnumerable<ArtStore.Models.ImageModel>

@{
    ViewBag.Title = "Index";
}

<h2>Index</h2>


@foreach (var item in Model)
{
    string path = item.ImageServerPath;
    <img src="@item.ImageServerPath" alt="Blah" />
}

what i'm not doing here?
Posted
Updated 22-Sep-14 11:17am
v4
Comments
[no name] 22-Sep-14 16:39pm    
"doesn't work" tells us nothing about your actual problem.

1 solution

Use
HTML
<img src="" /> 


First check the image is present in server folder or not, if not present download it from database to server folder.

Then you can directly use the image path like

HTML
<img src="/ImageFolderName/Subfoler/image.jpg">
</img>


Actually problem is

C#
@item.ImageServerPath


This variable contain image folder path of server..This full path is not required in browser. Use firebug check the image src..You will get more details about your error..
 
Share this answer
 
v2

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900