上传后使用viewbag显示图片 [英] Show image with viewbag after uploading

查看:131
本文介绍了上传后使用viewbag显示图片的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有这个:



I have this:

[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:

<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>







但是上传后图片被破坏并且在Chrome中我看到了网址:

< img src =/ Images / profile />



谢谢



我的imageUploadModel看起来像这样:






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:

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







但是我可以上传并且图像存储在正确的位置文件夹,但现在显示,坏了



oke,我这样做了:






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:

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:

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





然后我在Chrome中看到:



< img width =150 height =150>



but then I see in chrome this:

<img width="150" height="150">

推荐答案

对不起,当我第一次询问ImageUploadM时,我甚至没有偷看你的Razor odel。



在您的代码中,您正在设置Viewbag.Path,并且在您的剃刀中,您正在调用Viewbag.fileName。尝试改变一些事情:



在你的行动中:

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:
ViewBag.Path = String.Format("/Images/profile/{0}", fileName.Replace('+', '_'));





和你的剃刀:





and in your razor:

<th><img src="@Viewbag.Path" /></th>

这篇关于上传后使用viewbag显示图片的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆