Click here to Skip to main content
15,886,812 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I have 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" });
        }


and this is my view:

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

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

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

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




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

                        @*<div class="lifile">
                            @Html.ValidationMessageFor(m => m.file)
                            @Html.ValidationSummary(true)

                        </div>*@

                    </div>
                </div>

                <br />

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

                        <tr>
                          
                            <th><img src="@Url.Content(String.Format("/Images/profile/{0}", @ViewBag.fileName, 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>



But after uploading the image is broken and in Chrome I see that thr url is:
<img src="/Images/profile/">

Thank you

And my imageUploadModel looks like this:

SQL
public class ImageUploadModel
    {
        [Required(ErrorMessage = "Please Upload File")]
        [Display(Name = "Upload File")]
        [ValidateFile]
        public HttpPostedFileBase file { get; set; }
    }



But so I can upload and the images is stored in the correct folder, but now showing, broken

oke, I have done it like this:

C#
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.Replace('+', '_'));
               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));


and in the razor engine:

C#
<th><img width="150" height="150" src="@ViewBag.Path" /></th>


but then I see in chrome this:

<img width="150" height="150">
Posted
Updated 6-Jan-15 2:51am
v3
Comments
Nathan Minier 6-Jan-15 8:17am    
What's your ImageUploadModel look like?
[no name] 6-Jan-15 8:23am    
Iv updated my post

1 solution

I'm sorry, I didn't even peek at your Razor when I first asked about the ImageUploadModel.

In your code you're setting Viewbag.Path, and in your razor you're calling Viewbag.fileName. Try changing a couple things:

In your action:
C#
ViewBag.Path = String.Format("/Images/profile/{0}", fileName.Replace('+', '_'));


and in your razor:

HTML
<th><img src="@Viewbag.Path" /></th>
 
Share this answer
 
Comments
[no name] 6-Jan-15 8:51am    
Hi Nathan,

thank you for your reply, I have updated my post

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