使用实体框架mvc 4在服务器文件夹中上传图像并在Sql Server中保存路径

时间:2014-07-04 15:08:15

标签: asp.net-mvc entity-framework asp.net-mvc-4 entity-framework-5

我正在尝试使用实体框架将图片保存在Sqlserver 2008中的文件夹和存储路径中。我需要用图片注册用户。我的代码保存了除图片和图片路径之外的数据库中的所有数据。

My model is 

 {
    using System;
    using System.Collections.Generic;
    using System.ComponentModel.DataAnnotations;
    public partial class customer
    {

        [Display(Name="Username")]
        public string user_id { get; set; }

        [Display(Name = "Password")]
        public string password { get; set; }

        [Display(Name = "First Name")]
        public string first_name { get; set; }

        [Display(Name = "Last Name")]
        public string last_name { get; set; }

        [Display(Name = "Address")]
        public string address { get; set; }

        [Display(Name = "City")]
        public string city { get; set; }

        [Display(Name = "State")]
        public string state { get; set; }

        [Display(Name = "Zip")]
        public Nullable<int> zip { get; set; }

        [Display(Name = "Country")]
        public string country { get; set; }

        [Display(Name = "Email Address")]
        public string email { get; set; }

        [Display(Name = "Phone")]
        public string phone { get; set; }

        [Display(Name = "Picture")]
        public string picture { get; set; }

        [Display(Name = "Registration Date")]
        public Nullable<System.DateTime> reg_date { get; set; }

        [Display(Name = "Status")]
        public string status { get; set; }

        [Display(Name = "Keep me logged in")]
        public bool rememberme { get; set; }
     }
 }

My Controller is 

[HttpPost]
        public ActionResult Register(customer customer, HttpPostedFileBase file)
        {
            if (ModelState.IsValid)
            {
                if (file != null)
                {
                        file.SaveAs(HttpContext.Server.MapPath("~/image/") + file.FileName);
                        customer.picture = file.FileName;
                }
                onlinebookstoreEntities1 db = new onlinebookstoreEntities1();
                db.customers.Add(customer);
                db.SaveChanges();
                return RedirectToAction("Index","Home");
            }

            return View(customer);
        }


and my view is 


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


        <div class="editor-label">
            @Html.LabelFor(model => model.first_name)
        </div>
        <div class="txtreg">
            @Html.EditorFor(model => model.first_name)
        </div>

        <div class="editor-label">
            @Html.LabelFor(model => model.last_name)
        </div>
        <div class="txtreg">
            @Html.EditorFor(model => model.last_name)
        </div>

        <div class="editor-label">
            @Html.LabelFor(model => model.user_id)
        </div>
        <div class="txtreg">
            @Html.EditorFor(model => model.user_id)
        </div>

        <div class="editor-label">
            @Html.LabelFor(model => model.password)
        </div>
        <div class="txtreg">
            @Html.EditorFor(model => model.password)
        </div>

        <div class="editor-label">
            @Html.LabelFor(model => model.address)
        </div>
        <div class="txtreg">
            @Html.EditorFor(model => model.address)
        </div>

        <div class="editor-label">
            @Html.LabelFor(model => model.city)
        </div>
        <div class="txtreg">
            @Html.EditorFor(model => model.city)
        </div>

        <div class="editor-label">
            @Html.LabelFor(model => model.state)
        </div>
        <div class="txtreg">
            @Html.EditorFor(model => model.state)
        </div>

        <div class="editor-label">
            @Html.LabelFor(model => model.zip)
        </div>
        <div class="txtreg">
            @Html.EditorFor(model => model.zip)
        </div>

        <div class="editor-label">
            @Html.LabelFor(model => model.country)
        </div>
        <div class="txtreg">
            @Html.EditorFor(model => model.country)
        </div>

        <div class="editor-label">
            @Html.LabelFor(model => model.email)
        </div>
        <div class="txtreg">
            @Html.EditorFor(model => model.email)
        </div>

        <div class="editor-label">
            @Html.LabelFor(model => model.phone)
        </div>
        <div class="txtreg">
            @Html.EditorFor(model => model.phone)
        </div>

        <div class="editor-label">
            @Html.LabelFor(model => model.picture)
        </div>
        <div class="btnreg">
           <input type="file" id="picture" value="Upload Picture" />
        </div>


        <div class="txtreg">
            @Html.CheckBoxFor(model => model.rememberme)   @Html.LabelFor(model => model.rememberme)
        </div>

            <input type="submit" value="Create Account" name="btnsub" />

}

3 个答案:

答案 0 :(得分:0)

检查您的图片文件夹权限,如果没有,请将其设置为所有读取,写入和执行权限。尝试调试代码并检查文件是否为null或在 file.SaveAs 调用

时触发任何异常

答案 1 :(得分:0)

如果您想在数据库中保存图片,您的属性必须如下所示:

    [DisplayName("Billede")]
    [MaxLength]
    public byte[] PhotoFile { get; set; }

而不是:

       [Display(Name = "Picture")]
    public string picture { get; set; }

您可以像这样保存图片:

 @using (Html.BeginForm("Create", "Photo", FormMethod.Post, new { enctype = "multipart/form-data" }))
    {
                @Html.DisplayNameFor(model => model.PhotoFile)
                <input type="file" name="Image" />

PhotoController中的ActionResult方法将是

    public ActionResult Create(Photo photo, HttpPostedFileBase image)
    {

并实际保存照片本身

   if (image != null)
            {
                photo.ImageFileName = image.FileName;
                photo.ImageMimeType = image.ContentType;
                photo.PhotoFile = new byte[image.ContentLength];
                image.InputStream.Read(photo.PhotoFile, 0, image.ContentLength);
            }
            context.Add<Photo>(photo);
            context.SaveChanges();

希望你可以连接点。

穆罕默德

答案 2 :(得分:0)

将url保存到db非常简单。同时你可以在db中以字节格式保存图片。在你的客户模型中你有

方法-1: 将字符串类型或任何其他类型更改为字节。  因此,在此图片中,如果要保存图片,则将图片转换为字节类型,而不是db中客户表中的字符串。

//before
     [Display(Name = "Picture")]
        public string picture { get; set; }
    //After changing in db you add the table  in entity framework .edmx  and now it becomes
     [Display(Name = "Picture")]
        public byte[] picture { get; set; }

下面是您在db。中以字节格式保存图片的代码。

在您的控制器中

public ActionResult Register(customer model)
{
                        string ImageName = Path.GetFileName(file.FileName);
                        string physicalPath = Server.MapPath("~/images/" + ImageName);
                        file.SaveAs(physicalPath);
                        customer newRecord = new customer ();
                        newRecord.username= customer.username;
                        \\Assign for remaining feilds in table in this way.

                        using (MemoryStream ms = new MemoryStream())
                        {
                            file.InputStream.CopyTo(ms);
                            byte[] picArray = ms.GetBuffer();
                            newRecord.picture= picArray ;
                        }
            onlinebookstoreEntities1 db = new onlinebookstoreEntities1();
            db.customers.Add(newRecord);
            db.SaveChanges();

            }

在您的注册视图中

<div>
    @using (Html.BeginForm("ConfigAssetData", "Home", new { @tabno = "3" },      FormMethod.Post, new { enctype = "multipart/form-data", @class = "form-horizontal" }))
                    {



<div class="editor-label">
        @Html.LabelFor(model => model.first_name)
</div>
<div class="txtreg">
    @Html.EditorFor(model => model.first_name)
</div>

<div class="editor-label">
    @Html.LabelFor(model => model.last_name)
</div>
<div class="txtreg">
    @Html.EditorFor(model => model.last_name)
</div>

<div class="editor-label">
    @Html.LabelFor(model => model.user_id)
</div>
<div class="txtreg">
    @Html.EditorFor(model => model.user_id)
</div>

<div class="editor-label">
    @Html.LabelFor(model => model.password)
</div>
<div class="txtreg">
    @Html.EditorFor(model => model.password)
</div>

<div class="editor-label">
    @Html.LabelFor(model => model.address)
</div>
<div class="txtreg">
    @Html.EditorFor(model => model.address)
</div>

<div class="editor-label">
    @Html.LabelFor(model => model.city)
</div>
<div class="txtreg">
    @Html.EditorFor(model => model.city)
</div>
  @*UploadFile*@
**<input type="file" class="file-input" name="file"/>**

 @*Similar code here...*@

 }
 </div>

方法-2: 特别是在您需要保存图片路径的情况下,您需要做的是: - 在你的控制器

 public ActionResult Register(customer model)
{
                        string ImageName = Path.GetFileName(file.FileName);
                        string physicalPath = Server.MapPath("~/images/" + ImageName);
                        file.SaveAs(physicalPath);
                        customer newRecord = new customer ();
                        newRecord.username= customer.username;
                        //.......saving picture url......
                        newRecord.picture = physicalPath;
                        //Assign for remaining feilds in table in this way.

            onlinebookstoreEntities1 db = new onlinebookstoreEntities1();
            db.customers.Add(newRecord);
            db.SaveChanges();

             }

如果右键单击images文件夹并单击&#34;在Windows资源管理器中打开文件夹&#34;你可以看到你的照片上传。