Click here to Skip to main content
15,887,485 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
HI everybody,

I can upload and image. But it doesnt show the image.

this I have for uploading image:

C#
[HttpPost]
        public ActionResult EditPhotos(ImageUploadModel ImageUpload)
        {

            if (ModelState.IsValid)
            {

                var DirSeparator = Path.DirectorySeparatorChar;
                var fileName = Path.GetFileName(ImageUpload.file.FileName);
                
                var path = Server.MapPath("@\\Images\\profile" + DirSeparator + fileName.Replace('+', '_'));
               
                ImageUpload.file.SaveAs(path);
                ViewBag.Message = "File has been uploaded successfully";
                //ModelState.Clear();


                string username = User.Identity.Name;
                // Get the userprofile
                UserProfile user = db.userProfiles.FirstOrDefault(u => u.UserName.Equals(username));

                // Update fields

                byte[] uploadedFile = new byte[ImageUpload.file.ContentLength];
                ImageUpload.file.InputStream.Read(uploadedFile, 0, ImageUpload.file.ContentLength);
                user.file = uploadedFile;
                user.ImageMimeType = ImageUpload.file.ContentType;

                db.Entry(user).State = EntityState.Modified;

                try
                {
                    db.SaveChanges();
                }
                catch (DbEntityValidationException e)
                {
                    foreach (var eve in e.EntityValidationErrors)
                    {
                        Console.WriteLine("Entity of type \"{0}\" in state \"{1}\" has the following validation errors:",
                            eve.Entry.Entity.GetType().Name, eve.Entry.State);
                        foreach (var ve in eve.ValidationErrors)
                        {
                            Console.WriteLine("- Property: \"{0}\", Error: \"{1}\"",
                                ve.PropertyName, ve.ErrorMessage);
                        }
                    }
                    throw;
                }

            }

            //return View(); 

            return RedirectToAction("Edit", routeValues: new { controller = "Account", activetab = "tabs-2" });
        }





and this for getting the image:

C#
public ActionResult GetImage(int id)
       {

           var stream = (from m in db.userProfiles where m.Id == id select m.file).FirstOrDefault();
          // byte[] image = db.userProfiles.Where(p => p.Id == id).Select(img => img.file).FirstOrDefault();
           //var stream = new MemoryStream(image.ToArray());

           return File(stream, "image/png");

       }


and this for the view:

C#
<div class="table-responsive">
                   <table class="table">

                       <tr>
                           <th><img width="200" height="150" src="@Url.Action("GetImage", "Account", new { id = Model.Id })"></th>


                       </tr>
                   </table>
               </div>


So I can upload the image and it is saving the image. But it doesnt show the image after uploading. I dit f12 in Chrome, and I see that the path is: src="/Account/GetImage/58" . What ofcourse is not correct. But how to change that?

Thank you
Posted
Comments
[no name] 4-Jan-15 0:18am    
Yes the path source will be that as because you are making a server side call to GetImage from the img src.
so it is better to make an ajax call and show the image on success. You are saving the streams not the path, so anyhow path will not come up.

Use below code and change path as per your requirements.

1. View

@using (Html.BeginForm("UploadExcel", "UserDetails", FormMethod.Post, new { enctype = "multipart/form-data" })) // ("Method name", "Controller name",post, type)
{
@Html.ValidationSummary(true)



@Html.LabelFor(model => model.Files)


<input type="file" name="fileupload" multiple="multiple" required="required"/>
@Html.ValidationMessageFor(model => model.Files)


<input type="submit" value="Create" />



}

2. Controller
[HttpPost]
public ActionResult UploadExcel(HttpPostedFileBase[] fileupload)
{
HttpPostedFileBase file = fileupload;
if (file == null)
{
ModelState.AddModelError("File", "Please Upload Your file");
}
else if (file.ContentLength > 0)
{
int MaxContentLength = 1024 * 1024 * 3; //3 MB
string[] AllowedFileExtensions = new string[] { ".jpg", ".gif", ".png", ".pdf" };
if (!AllowedFileExtensions.Contains(file.FileName.Substring(file.FileName.LastIndexOf('.'))))
{
ViewBag.Message = "File, Please file of type: " + string.Join(", ", AllowedFileExtensions);
}
else if (file.ContentLength > MaxContentLength)
{
ViewBag.Message = "File, Your file is too large, maximum allowed size is: " + MaxContentLength + " MB";
}
else
{
//TO:DO
var fileName = Path.GetFileName(file.FileName);
var path = Path.Combine(Server.MapPath("~/Content/Upload"), fileName);
file.SaveAs(path);
ModelState.Clear();
ViewBag.Message = "File uploaded successfully";
}
}
return View();
}
 
Share this answer
 
HI,

thank you for your answare. But where you have to code for seeing the image after uploading.

I have the view like this:

C#
<div id="tabs-2">

       @using (Html.BeginForm("EditPhotos", "Account", new { id = "form", enctype = "multipart/form-data" }))
       {
           @Html.AntiForgeryToken()

           <div class="form-horizontal">
               <h4>Photos</h4>
               <hr />

               @Html.HiddenFor(model => model.Id)



               <div class="lifile">
                   <div id="upload-choices">
                       <div class="editor-label">


                           @Html.ValidationMessageFor(model => model.file)
                           @Html.ValidationSummary(true)

                       </div>

                   </div>
               </div>

               <br />

               <div class="table-responsive">
                   <table class="table">

                       <tr>
                           @*<th></th>*@
                         <th><img width="200" height="150" src="@Url.Action(" account=", new { id = Model.Id})" /></th>




                       </tr>
                   </table>
               </div>

               <input type="file" name="File" class="filestyle" data-buttontext="Find file">



               <br />
               <div class="progress progress-striped">
                   <div class="progress-bar progress-bar-success">0%</div>
               </div>

               <div id="status"></div>


               <br />

               @*@Html.ActionLink("Upload photos", "Upload")*@

               <div class="pull-left">
                   <div class="col-md-offset-0">
                       <input type="submit" value="Save" accept="image/x-png, image/gif, image/jpeg" class="btn btn-default pull-left" />

                   </div>
               </div>

           </div>
       }

       <br /><br />
       <div>
           @Html.ActionLink("Back to List", "Index")
       </div>
   </div>



and the method, like this:


C#
[HttpPost]
       public ActionResult EditPhotos(ImageUploadModel ImageUpload)
       {

           if (ImageUpload.file == null || ImageUpload.file.ContentLength == 0)
           {
               ModelState.AddModelError("file", "This field is requird");
           }

           if (ModelState.IsValid)
           {

               var DirSeparator = Path.DirectorySeparatorChar;
               var fileName = Path.GetFileName(ImageUpload.file.FileName);

               var path = Path.Combine(Server.MapPath(@"\\Images\\profile" + @"\" + fileName.Replace('+', '_')));

               ImageUpload.file.SaveAs(path);
               ViewBag.Path = String.Format("/Images/profile/{0}", fileName);
               ViewBag.Message = "File has been uploaded successfully";
               //ModelState.Clear();


               string username = User.Identity.Name;
               // Get the userprofile
               UserProfile user = db.userProfiles.FirstOrDefault(u => u.UserName.Equals(username));

               // Update fields

               byte[] uploadedFile = new byte[ImageUpload.file.ContentLength];
               ImageUpload.file.InputStream.Read(uploadedFile, 0, ImageUpload.file.ContentLength);
               user.file = uploadedFile;
               user.ImageMimeType = ImageUpload.file.ContentType;

               db.Entry(user).State = EntityState.Modified;

               try
               {
                   db.SaveChanges();
               }
               catch (DbEntityValidationException e)
               {
                   foreach (var eve in e.EntityValidationErrors)
                   {
                       Console.WriteLine("Entity of type \"{0}\" in state \"{1}\" has the following validation errors:",
                           eve.Entry.Entity.GetType().Name, eve.Entry.State);
                       foreach (var ve in eve.ValidationErrors)
                       {
                           Console.WriteLine("- Property: \"{0}\", Error: \"{1}\"",
                               ve.PropertyName, ve.ErrorMessage);
                       }
                   }
                   throw;
               }

           }

           //return View();

           return RedirectToAction("Edit", routeValues: new { controller = "Account", activetab = "tabs-2" });
       }


but still not showing the image

Now the output is like this:

C#
<img width="200" height="150" src="/Account/%40ViewBag.path/58">


But this has to be the path:

G:\Mijn Documents\My Web Sites\Lolabikes - Copy\C#\ContosoUniversity\Images\profile\6a00d8341c562c53ef0148c82ff5d1970c-800wi.jpg
 
Share this answer
 
v3

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