图像不保存到SQL和文件夹

时间:2015-11-19 09:43:11

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

我是MVC的初学者,我开发了Image Uploader,它真的很有用,但那个图像没有保存我的上传文件夹和数据库,请帮帮我。 view this image模型

         namespace eData
{
    public class Clr
    {

        [Key]
        public int ClrID { get; set; }
        [StringLength(5, ErrorMessage = "Must be 5 characters", MinimumLength = 5)]
        [Required(ErrorMessage = "Required")]

        public string ClrCode { get; set; }


             [StringLength(25, ErrorMessage = "Must be less than 25 charcters", MinimumLength = 1)]
        [Required(ErrorMessage = "Required")]
        public string ClrName { 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 Name { get; set; }
    public int Length { get; set; }
    public string Type { get; set; }
    }
}

Clr控制器(创建部件)

public class ClrController : Controller
    {
        // GET: Masters/Clr
        //public ActionResult Index()
        //{
        //    return View();
        //}

        public FilePathResult Image()
        {
            string filename = Request.Url.AbsolutePath.Replace("/Clr/image", "");
            string contentType = "";
            var filePath = new FileInfo(Server.MapPath("~/Uploaded") + filename);

            var index = filename.LastIndexOf(".") + 1;
            var extension = filename.Substring(index).ToUpperInvariant();

            // Fix for IE not handling jpg image types
            contentType = string.Compare(extension, "JPG") == 0 ? "image/jpeg" : string.Format("image/{0}", extension);

            return File(filePath.FullName, contentType);
        }

        [HttpPost]
        public ContentResult UploadFiles()
        {
            var r = new List<UploadFilesResult>();

            foreach (string file in Request.Files)
            {
                HttpPostedFileBase hpf = Request.Files[file] as HttpPostedFileBase;
                if (hpf.ContentLength == 0)
                    continue;

                string savedFileName = Path.Combine(Server.MapPath("~/Uploaded"), Path.GetFileName(hpf.FileName));
                hpf.SaveAs(savedFileName);

                r.Add(new UploadFilesResult()
                {
                    Name = hpf.FileName,
                    Length = hpf.ContentLength,
                    Type = hpf.ContentType
                });
            }
            return Content("{\"name\":\"" + r[0].Name + "\",\"type\":\"" + r[0].Type + "\",\"size\":\"" + string.Format("{0} bytes", r[0].Length) + "\"}", "application/json");
        }


        public ActionResult Save(Clr clr)
        {
            var objContext = new KktdbContext();
            clr.CreateBy = 1;
            clr.StatusChangeDate = System.DateTime.Now;
            clr.CreatedDate = System.DateTime.Now;
            clr.EditBy = 1;
            clr.EditDate = System.DateTime.Now;
            objContext.Clrs.Add(clr);
            objContext.SaveChanges();
            TempData["Success"] = "Saved Sucessfully";
            return RedirectToAction("ClrIndex", new { A = "New" });


        }

查看-Create.chtml

@using (@Html.BeginForm("Save", "Clr"))
        {
            <div class="col-md-6" style="font-family:Arial, Helvetica, sans-serif; font-size:13px;"> <b>Clr Code</b> <b style=" color:#ff0000;">*</b> </div>

 <div class="col-md-6">
                @Html.TextBoxFor(a => a.ClCode, new { Class = "form-control", placeholder = " Clr Code", TextMode = "MultiLine2", onkeyup = "return validateChar(this)", maxlength = "6", style = "width:175px;height:25px; margin-top:6px;" })
                <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.ClrCode)
            </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>Clr Name</b> <b style=" color:#ff0000;">*</b> </div>
            <div class="col-md-6">
                @Html.TextBoxFor(a => a.ClrName, new { @maxlength = "15", Class = "form-control", placeholder = "Clr Name", style = "width:175px;height:25px;margin-top:6px;" })
                @Html.ValidationMessageFor(a => a.ClrName)
            </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">@Html.TextAreaFor(a => a.Remarks, new { style = "width: 250px; resize: none; height: 65px;;margin-top:6px;", 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"></div> <div class="col-md-6"></div>

            <div class="col-md-6"></div>
            <div class="col-md-6">   <input type="submit" value="Save" class="btn btn-success" /> </div>
        }
    </div>
    <!--Saved Successfully Message-->
    @if (TempData["Success"] != null)
    {
        <div class="green">
            <p style="color:green; font-family:'Arno Pro'; font-size:14px; position: absolute; margin-left:250px; margin-top:-25px;">Saved Successfully</p>
        </div>
    }
    <!--End Sved Successfully Message-->

    <div class="container">
        <span class="btn btn-success fileinput-button">
            <i class="glyphicon glyphicon-plus"></i>
            <span>Add files...</span>
            <input id="fileupload" type="file" name="files[]" multiple onchange="loadFile(event)">
        </span>
        <br />
        <div class="progress" style="width:500px;">


            <div class="progress-bar progress-bar-success" role="progressbar" aria-valuenow="0" aria-valuemin="0" aria-valuemax="100" style="width:0%">
                100% Complete (success)
            </div>
        </div>
        <br />
        <div class="file_name"></div>
        <br />
        <div class="file_type"></div>
        <br />
        <div class="file_size"></div>

        <a class="fancybox">
            <img id="output" style="width:200px; height:200px;" />

        </a>

        <script>
            var loadFile = function (event) {
                var output = document.getElementById('output');
                output.src = URL.createObjectURL(event.target.files[0]);
            };
        </script>
<script type="text/javascript">
    $(document).ready(function () {
        $('#fileupload').fileupload({
            dataType: 'json',
            url: '"~/Clr/UploadFiles',
            autoUpload: true,
            done: function (e, data) {
                $('.file_name').html(data.result.name);
                $('.file_type').html(data.result.type);
                $('.file_size').html(data.result.size);

            }
        }).on('fileuploadprogressall', function (e, data) {
            var progress = parseInt(data.loaded / data.total * 100, 10);
            $('.progress .progress-bar').css('width', progress + '%');
        });
    });
    </script>


        <script>
            $("#output")
                .attr('rel', 'output')
                .fancybox({
                    padding: 0
                });</script>
    </div>

1 个答案:

答案 0 :(得分:2)

在您的视图中使用此代码

Html.BeginForm("Save", "Clr", FormMethod.Post, enctype = "multipart/form-data")