上传的图像不是网格视图中的显示

时间:2015-11-23 07:31:22

标签: asp.net-mvc asp.net-mvc-4

我是MVC的初学者,仍然在 MVC 中学习,我已经开始 MVC图片上传,它真的很有效,但在我的中没有显示上传的图片网格视图,我该如何解决?请帮帮我,或者有人请一步一步给我示例代码,我需要为usrers脚本上传图片编辑删除,总是在SQL中获取 null vlaue image  here

模型

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.ComponentModel.DataAnnotations;

namespace eKnittingData
{
   public class Component
    {
        [Key]
        public int ComponentId { get; set; }
        [StringLength(5, ErrorMessage = "Must be 5 characters", MinimumLength = 5)]
        [Required(ErrorMessage = "Required")]
        public string ComponentCode { get; set; }
        [StringLength(25, ErrorMessage = "Must be less than 25 charcters", MinimumLength = 1)]
        [Required(ErrorMessage = "Required")]

        public string ComponentName { get; set; }


        public string Remarks { get; set; }

        public bool StatusId { get; set; }


        public DateTime StatusChangeDate { get; set; }

        public int CreateBy { get; set; }

        public DateTime CreatedDate { get; set; }

        public int EditBy { get; set; }

        public DateTime EditDate { get; set; }

        public string MyProperty1 { get; set; }
        public string MyProperty2 { get; set; }
        public string MyProperty3 { get; set; }
        public string FileName { get; set; }
    }
}

控制器

 public ActionResult Save(Component component, HttpPostedFileBase file)
        {
            var objContext = new KnittingdbContext();
            component.CreateBy = 1;
            component.StatusChangeDate = System.DateTime.Now;
            component.CreatedDate = System.DateTime.Now;
           component.EditBy = 1;
            component.EditDate = System.DateTime.Now;
            objContext.Components.Add(component);
            objContext.SaveChanges();
            string fileName = string.Empty; ;
            if (file != null && file.ContentLength > 0)
            {
                // extract only the fielname
                fileName = Path.GetFileName(file.FileName).ToString();
                // store the file12 inside ~/App_Data/uploads folder
                var path = Path.Combine(Server.MapPath("~/Uploaded"), fileName);
                file.SaveAs(path);
            }

            TempData["Success"] = "Saved Sucessfully";

            return RedirectToAction("ComponentIndex", new { A = "New" });
        }

索引

     <table class="table" style="top:-35px; position:relative; width:910px; margin-left:4px;">



                    <tr>

                        <th class="col-sm-3">@Html.ActionLink("Component Code", "ComponentIndex", new { sortOrder = ViewBag.NameSortParm, currentFilter = ViewBag.CurrentFilter }, new { Style = "color:white;text-decoration: none;" })</th>
                        <th class="col-sm-3">@Html.ActionLink("Component Name", "ComponentIndex", new { sortOrder = ViewBag.NameSortParm, currentFilter = ViewBag.CurrentFilter }, new { Style = "color:white;text-decoration: none;" })</th>
    <th>img</th>
                        <th class="col-sm-3" style="color:#ffffff;">img</th>

                        <th class="col-sm-3" style="color:#ffffff;">Remarks</th>
                        <th style="color:#ffffff;">Status</th>
                        <th></th>


                    </tr>


                    @foreach (var item in Model)
                    {




                        <tr>
                            <td class="col-sm-3">@item.ComponentCode</td>
                            <td>@item.ComponentName</td>
                            <td>@item.FileName</td>
<td><td class="col-sm-3"><img src="@Url.Action("FileName", "Component", new { id = item.FileName })" alt="@item.FileName" /></td></td>
                            <td style="height:auto;  word-wrap: break-word;max-width:50px;display:table-cell;
       vertical-align: top;">
                                @item.Remarks
                            </td>

                            <td class="col-sm-1">
                                @if (item.StatusId)
                                {
                                    <span>Active</span>
                                }
                                else
                                {
                                    <span>Inactive</span>
                                }
                            </td>



                            <td class="col-sm-1">@Html.ActionLink("Edit", "ComponentIndex", "Component", new { A = "Edit", Id = item.ComponentId }, new { Class = "btn btn-info", style = " line-height:10px;left:2px;background-color:#24ade3; position:relative; width:65px;" })</td>





                        </tr>


                    }








                </table>

创建

    @using (Html.BeginForm("Save", "Component", FormMethod.Post, new { enctype = "multipart/form-data" }))
    {

        <div class="col-md-6" style="font-family:Arial, Helvetica, sans-serif; font-size:13px;"><b>Component Code</b><b style=" color:#ff0000;">*</b></div>

        <div class="col-md-6">
            @Html.TextBoxFor(a => a.ComponentCode, new { @maxlength = "5", Class = "form-control", style = "width:175px; height:25px;font-size:small;", onkeyup = "return validateChar(this)", placeholder = "Component Code" })
            <div id="fname_error" style="margin-left:180px; width:140px;     top:5px; color:green; position:absolute; font-family:'Arial Unicode MS'; font-size:small;"></div>
            @Html.ValidationMessageFor(a => a.ComponentCode)
        </div>
        <div class="col-md-6"></div>    <div class="col-md-6"></div>
        <div class="col-md-6" style="font-family:Arial, Helvetica, sans-serif; font-size:13px;margin-top:5px;">
            <b>Component</b><b style=" color:#ff0000;">*</b>
        </div>
        <div class="col-md-6">
            @Html.TextBoxFor(a => a.ComponentName, new { @maxlength = "25", Class = "form-control", style = "width:175px;height:25px;margin-top:6px;font-size:small;", placeholder = "Component" })
            @Html.ValidationMessageFor(a => a.ComponentName)
        </div>            <div class="col-md-6"></div>    <div class="col-md-6"></div>

        <div class="col-md-6" style="font-family:Arial, Helvetica, sans-serif; font-size:13px;">
            <b>Remarks</b>
        </div><div class="col-md-6"></div>    <div class="col-md-6"></div>
        <div class="col-md-6">
            @Html.TextAreaFor(a => a.Remarks, new { style = "width: 250px; height: 65px; resize: none;margin-top:6px;font-size:small;", Class = "form-control", })
        </div>            <div class="col-md-6"></div>    <div class="col-md-6"></div>
        <div class="col-md-6" style="font-family:Arial, Helvetica, sans-serif; font-size:13px;">
            <b>   Status </b>
        </div>

        <div class="col-md-6">
            @Html.CheckBoxFor(a => a.StatusId)
        </div>

        <div class="col-md-6">
            @Html.HiddenFor(a => a.ComponentId)
        </div>
        <div class="col-md-6"></div>    <div class="col-md-6"></div>
        <div class="col-md-6">
            <input type="submit" value="Save" id="btn" class="btn btn-success" />
        </div>

          <div>
@Html.LabelFor(x => x.MyProperty1)
@Html.EditorFor(x => x.MyProperty1) </div>
<div>
@Html.LabelFor(x => x.MyProperty1)
@Html.EditorFor(x => x.MyProperty2)</div>
<div>
@Html.LabelFor(x => x.MyProperty1)
@Html.EditorFor(x => x.MyProperty3)</div>


<div><input type="file" name="file" id="file" /> </div>

    }

更新控制器

 public ActionResult Update(Component component, HttpPostedFileBase file)
        { 
            string fileName = string.Empty;
            if (file != null && file.ContentLength > 0)
            {
                // extract only the fielname
                fileName = Path.GetFileName(file.FileName);
                // store the file12 inside ~/App_Data/uploads folder
                var path = Path.Combine(Server.MapPath("~/Uploaded"), fileName);
                file.SaveAs(path);


                var objContext = new KnittingdbContext();
                //blog.Id = 1;
                objContext.Components.Attach(component);
                var obJBlog = objContext.Entry(component);

                obJBlog.Property(a => a.ComponentCode).IsModified = true;
                obJBlog.Property(a => a.ComponentName).IsModified = true;
                obJBlog.Property(a => a.Remarks).IsModified = true;
                obJBlog.Property(a => a.StatusId).IsModified = true;



                objContext.SaveChanges();

                TempData["SuccessEdit"] = "Saved Sucessfully";

                return RedirectToAction("ComponentIndex");
            }
            else
            {
                return PartialView("_ComponentEdit", component);
            }
        }

2 个答案:

答案 0 :(得分:1)

如我的评论中所述,您必须在保存颜色时上传颜色和图像文件之间的关系。

现在假设您在颜色表中有一个文件名,您可以在代码下面使用它来显示您的图像。

Razor Code:

<img src="@Url.Action("GetImage", "YourController", new { fileName = item.FileName })" alt="@item.FileName" />

现在,GetImage的控制器动作方法如下所示。

public ActionResult GetImage(string fileName)
{
    System.Drawing.Image img = System.Drawing.Image.FromFile(HttpContext.Server.MapPath("~/Uploaded/") + fileName);
    byte[] bytes;
    using (MemoryStream ms = new MemoryStream())
    {
        img.Save(ms, System.Drawing.Imaging.ImageFormat.Jpeg);
        bytes = ms.ToArray();
    }
    return File(img, "image/jpg");
}

选项2:

您可以直接将图像保存到颜色表中的数据库中。在这种情况下,您可以直接绘制您的图像,如下所示。

<img src="data:image/jpg;base64,@(Convert.ToBase64String(item.Image))" alt="@item.Color" />

有关此内容的更多详情,请参阅this blog post

答案 1 :(得分:1)

保存FileName时需要保存Component,并确保在项目的根目录中有一个名为Uploaded的文件夹。您的Save操作应该如下。

public ActionResult Save(Component component, HttpPostedFileBase file)
    {   
        string fileName = string.Empty;
        if (file != null && file.ContentLength > 0)
        {
            // extract only the fielname
            fileName = Path.GetFileName(file.FileName);
            // store the file12 inside ~/App_Data/uploads folder
            var path = Path.Combine(Server.MapPath("~/Uploaded"), fileName);
            file.SaveAs(path);
        }

        var objContext = new KnittingdbContext();
        component.CreateBy = 1;
        component.StatusChangeDate = System.DateTime.Now;
        component.CreatedDate = System.DateTime.Now;
        component.EditBy = 1;
        component.EditDate = System.DateTime.Now;
        //file name added here
        component.FileName = fileName;  
        objContext.Components.Add(component);
        objContext.SaveChanges();

        TempData["Success"] = "Saved Sucessfully";

        return RedirectToAction("ComponentIndex", new { A = "New" });
    } 

要获取图片,您的FileName操作应该如下。

public ActionResult FileName(string id)
{
    byte[] image = { };

    try
    {
        image = System.IO.File.ReadAllBytes(Server.MapPath("~/Uploaded/") + id);
    }
    catch { }

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

<强>更新

UpdateSave行为类似。要更新,您必须获取以前的记录然后更新它。请参阅下面的代码。

public ActionResult Update(Component component, HttpPostedFileBase file)
    {
        var objContext = new KnittingdbContext();
        var oldComponent = objContext.Components.Find(component.ComponentId);

        string fileName = string.Empty;
        if (file != null && file.ContentLength > 0)
        {
            //delete old file
            var oldFilePath = Path.Combine(Server.MapPath("~/Uploaded"), oldComponent.FileName);
            if ((System.IO.File.Exists(oldFilePath)))
            {
                System.IO.File.Delete(oldFilePath);
            }

            // extract only the fielname
            fileName = Path.GetFileName(file.FileName);
            // store the file12 inside ~/App_Data/uploads folder
            var path = Path.Combine(Server.MapPath("~/Uploaded"), fileName);
            file.SaveAs(path);
        }

        oldComponent.ComponentName = oldComponent.ComponentName;
        oldComponent.Remarks = oldComponent.Remarks;
        oldComponent.StatusId = oldComponent.Remarks;
        //and more properties goes here

        oldComponent.CreateBy = 1;
        oldComponent.StatusChangeDate = System.DateTime.Now;
        oldComponent.CreatedDate = System.DateTime.Now;
        oldComponent.EditBy = 1;
        oldComponent.EditDate = System.DateTime.Now;
        oldComponent.FileName = fileName;

        objContext.SaveChanges();

        TempData["Success"] = "Updated Sucessfully";

        return RedirectToAction("ComponentIndex", new { A = "New" });
    }
相关问题