【问题标题】:How to upload file at same time as other data如何与其他数据同时上传文件
【发布时间】:2023-03-30 05:40:01
【问题描述】:

我在表单中上传了文件,但我无法将其与其他元素同时保存在同一模型或两个单独的模型中。我知道我的第一个问题是我不能嵌套表单,例如

@using (Html.BeginForm("Create", "Home", FormMethod.Post, new { enctype = "multipart/form-data" }))
{
    <form class="form-horizontal">
       <input />
       <input />
           @using (Html.BeginForm("Create", "Home", FormMethod.Post, new { enctype = "multipart/form-data" }))
           {
              <form class="form-horizontal">
              <input image upload/>
              <input />

             </form>
           }
    </form>
}

所以我现在有两个单独的表单并且可以很好地工作,但我想要一些东西: 1.当用户选择图像上传任何当前输入的不被删除的值时 2.将所有输入数据(所有表单元素)与图像一起更新到所选模型。 3.有没有办法以一种形式做到这一点? (在一个 r 中!)。

我将如何实现这一目标?我目前的工作如下。

查看:

 @model client.Models.jobs

@{
    ViewBag.Title = "Create Job Details";
}

<br /><br /><br />
@using (Html.BeginForm("Create", "Home", FormMethod.Post, new { enctype = "multipart/form-data" }))
{
    <form class="form-horizontal">
        <fieldset>
            <legend>Job Details</legend>

            <!--Postcode search--><label for="inputEmail" class="col-lg-2 control-label">Job's Name</label>
            <input name="jobname" type="text" placeholder="Job Name" /><br /><br />


            <label for="jobdescription" class="col-lg-2 control-label">Job Description</label>
            <br /><br />
            <div class="col-lg-10">
                <textarea class="form-control" rows="3" name="textArea" placeholder="Write here..."></textarea>
                <span class="help-block">The more details you enter the easier the Tradesmen can work</span>
            </div>

            <br /><br /><br /><br /><br /><br />
            <label for="uploadphotos" class="col-lg-2 control-label">
                Add PHOTOS (Optional)

                @Html.LabelFor(model => model.ImageData, new { @class = "control-label col-md-2" })
                <input name="Image" type="file" />
                @Html.ValidationMessageFor(model => model.ImageData)

                <button type="submit" value="Upload" onclick="location.href='@Url.Action("Create", "Home")'">Upload</button>
                @ViewBag.Message

            </label>


            <br /><br />
            <label for="select" class="col-lg-2 control-label">Tell us which stage you’re at</label>
            <div class="col-lg-10">
                <select class="form-control" name="stage">
                    <option>Preplan</option>
                    <option>already started</option>
                    <option>Almost finished</option>
                    <option>Needs redone fully</option>
                </select>
            </div>
            <br /><br /><br /><br />

            <label for="select" class="col-lg-2 control-label"> When would you like the job to start?*</label>
            <div class="col-lg-10">
                <select class="form-control" name="startjob">
                    <option>ASAP</option>
                    <option>1-2 weeks</option>
                    <option>1 month</option>
                    <option>1+</option>
                </select>
            </div>
            <br /><br /><br /><br />
            <label for="select" class="col-lg-2 control-label">What's your approximate budget?</label>
            <div class="col-lg-10">
                <select class="form-control" name="budget">
                    <option>£0-500</option>
                    <option>£500-100</option>
                    <option>£1000-2000</option>
                    <option>£2000+</option>
                </select>
            </div>


            <br /><br /><br /><br />





    </form>
}


@using (Html.BeginForm("getJobFormValues", "Home", FormMethod.Post, new { enctype = "multipart/form-data" }))
{
    <form class="form-horizontal">
        <input name="jobname" type="text" placeholder="Job Name" /><br /><br />
            <button type="submit" class="btn btn-success btn-lg">Next</button>

     </form>

}

@section Scripts{
   <script>
      debugger
   </script>
}

控制器和动作:

[AcceptVerbs(HttpVerbs.Post)]
        public ActionResult Create(uploadedfiles pic, HttpPostedFileBase image)
        {
            if (ModelState.IsValid)
            {
                if (image != null)
                {
                    //attach the uploaded image to the object before saving to Database
                    pic.ContentType = Convert.ToString(image.ContentLength);
                    pic.ImageData = new byte[image.ContentLength];
                    image.InputStream.Read(pic.ImageData, 0, image.ContentLength);

                    //Save image to file
                    var filename = image.FileName;
                    var filePathOriginal = Server.MapPath("/Content/Uploads/Originals");
                    var filePathThumbnail = Server.MapPath("/Content/Uploads/Thumbs");
                    string savedFileName = Path.Combine(filePathOriginal, filename);
                    image.SaveAs(savedFileName);

                    //Read image back from file and create thumbnail from it
                    var imageFile = Path.Combine(Server.MapPath("~/Content/Uploads/Originals"), filename);
                    using (var srcImage = Image.FromFile(imageFile))
                    using (var newImage = new Bitmap(100, 100))
                    using (var graphics = Graphics.FromImage(newImage))
                    using (var stream = new MemoryStream())
                    {
                        graphics.SmoothingMode = SmoothingMode.AntiAlias;
                        graphics.InterpolationMode = InterpolationMode.HighQualityBicubic;
                        graphics.PixelOffsetMode = PixelOffsetMode.HighQuality;
                        graphics.DrawImage(srcImage, new Rectangle(0, 0, 100, 100));
                        newImage.Save(stream, ImageFormat.Png);
                        var thumbNew = File(stream.ToArray(), "image/png");
                        pic.ImageData = thumbNew.FileContents;
                        pic.ImageName = filename;
                    }
                }

                //Save model object to database
                db.uploadedfiles.Add(pic);

                ViewBag.Message = "Image Uploaded Successfully!!";

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

                ViewBag.Message = "Image Uploaded Successfully!!";

                return View("JobDetails");
               //return RedirectToAction("getJobFormValues");

            }

            return View("JobDetails");
        }

 [HttpPost]
        public ActionResult getJobFormValues(jobs job)
        {
            string quoteSearch = Request["quoteSearch"];
            string jobname = Request["jobname"];
            string jobmessage = Request["textArea"];
            string uploadedphoto = Request["uploadphotos"];
            string stage = Request["stage"];
            string startjob = Request["startjob"];
            string budget = Request["budget"];
            int imgid = 2;



            //Save model object to database
            //Save personal details model object to database
            if (ModelState.IsValid)
            {

                //Save model object to database
                db.jobs.Add(new jobs
                {
                    name = jobname,
                    jobmessage = jobmessage,
                    //iscomplete
                    //jobbyuserid
                    //responsibletradesmanid
                    //jobmessage
                    stage = stage,
                    startjob = startjob,
                    budget = Convert.ToInt32(budget),
                    ImageId = imgid
                    //ImageName
                    //ImageAlt
                    //ImageData
                    //ContentType
                });

                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 RedirectToAction("PersonalDetails", new
                {
                    quoteSearch = quoteSearch,
                    jobname = jobname,
                    jobmessage = jobmessage,
                    uploadedphoto = uploadedphoto,
                    stage = stage,
                    startjob = startjob,
                    budget = budget
                });
            }//model state

            return View("JobDetails");

        }

【问题讨论】:

    标签: c# entity-framework file-upload asp.net-mvc-5


    【解决方案1】:
    I hope this will help anyone in same situation(i.e. learners!). After hunting around I realised that if (I could be wrong!) working with complex objects such as images text will just be strung along anyway with the .Add and .Save as long as they're part of the Model like so:
    namespace client.Models
    {
        using System;
        using System.Collections.Generic;
    
        public partial class jobs
        {
            public int id { get; set; }
            public string name { get; set; }
            public Nullable<bool> iscomplete { get; set; }
            public Nullable<int> jobbyuserid { get; set; }
            public Nullable<int> responsibletradesmanid { get; set; }
            public string jobmessage { get; set; }
            public string stage { get; set; }
            public string startjob { get; set; }
            public int ImageId { get; set; }
            public string ImageName { get; set; }
            public string ImageAlt { get; set; }
            public byte[] ImageData { get; set; }
            public string ContentType { get; set; }
            public string Budget { get; set; }
        }
        }
    
    Then chop up the Action to create,hold,save,image data etc but MOST IMPORTANTLY you do not need to define any fields from the form 
       `(string quoteSearch = Request["quoteSearch"]; etc.)` as they will be updated with the model. So the only difference here is that I have removed the form requests and removed saving single items like  
    
          //Save model object to database
                        db.jobs.Add(new jobs
                        {
                            name = jobname,
    
    and then only used one action for both image and form data all put together nicely like so:
    
    
    
    
         [AcceptVerbs(HttpVerbs.Post)]
         public ActionResult Create(jobs pic, HttpPostedFileBase image)
         {
         var context = System.Web.HttpContext.Current;
        var contextBase = new HttpContextWrapper(context);
        ////Pull out the current username from cookie into var
        //usernameCookie = new HttpCookie("CurrentUsername");
        //usernameCookie = contextBase.User.Request.Cookies["CurrentUsername"];
    
            //Get email from OWIN
            string usernameCookie = contextBase.User.Identity.Name.ToString();
    
            if (ModelState.IsValid)
            {
                if (image != null)
                {
                    //attach the uploaded image to the object before saving to 
    
    
            Database
                        pic.ContentType = Convert.ToString(image.ContentLength);
                        pic.ImageData = new byte[image.ContentLength];
                        image.InputStream.Read(pic.ImageData, 0, 
           image.ContentLength);
    
                        //Save image to file
                        var filename = image.FileName;
                        var filePathOriginal = 
           Server.MapPath("/Content/Uploads/Originals");
                        var filePathThumbnail = 
           Server.MapPath("/Content/Uploads/Thumbs");
                        string savedFileName = Path.Combine(filePathOriginal, 
           filename);
                        image.SaveAs(savedFileName);
    
                        //Read image back from file and create thumbnail from it
                        var imageFile = 
            Path.Combine(Server.MapPath("~/Content/Uploads/Originals"), filename);
                        using (var srcImage = Image.FromFile(imageFile))
                        using (var newImage = new Bitmap(100, 100))
                        using (var graphics = Graphics.FromImage(newImage))
                        using (var stream = new MemoryStream())
                        {
                            graphics.SmoothingMode = SmoothingMode.AntiAlias;
                            graphics.InterpolationMode = 
            InterpolationMode.HighQualityBicubic;
                            graphics.PixelOffsetMode = PixelOffsetMode.HighQuality;
                            graphics.DrawImage(srcImage, new Rectangle(0, 0, 100, 
             100));
                            newImage.Save(stream, ImageFormat.Png);
                            var thumbNew = File(stream.ToArray(), "image/png");
                            pic.ImageData = thumbNew.FileContents;
                            pic.ImageName = filename;
                        }
                    }
    
                    //Save model object to database
                    db.jobs.Add(pic);
    
                    ViewBag.Message = "Image Uploaded Successfully!!";
    
                    int newJobID = 0;
    
                    try
                {
                    //this saves model with image
                    db.SaveChanges();
    
                    //get last inserted row ID
                    newJobID = pic.id;
    
                    //get row based on last inserted for updating the imageID as we want them correlate
                    // make sure you have the right column/variable used here
                    var rowToUpdate = db.jobs.FirstOrDefault(x => x.id == newJobID);
                    if (rowToUpdate == null) throw new Exception("Invalid id: " + newJobID);
                    // this variable is tracked by the db context
                    rowToUpdate.ImageId = newJobID;
    
                    var addLoggedInUserToTable = db.tradesusers.FirstOrDefault(e => e.email == usernameCookie);
                    if (addLoggedInUserToTable == null) throw new Exception("Invalid id: " + usernameCookie);
                    addLoggedInUserToTable.lastpostedjobid = newJobID;
    
                    if (addLoggedInUserToTable.email == usernameCookie) { 
                    rowToUpdate.jobbyuserid = addLoggedInUserToTable.id;
                }
    
                    //reasave Model with updated ID
                    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;
                }
    
                ViewBag.Message = "Image Uploaded Successfully!!";
    
                //return View("JobDetails");
                return RedirectToAction("PersonalDetails", new { usernameCookie = usernameCookie });
    
            }
    
            return View("JobDetails");
        }`enter code here`
    
    I believe retrieving the images is a bit more straight forward! ;-)
    

    【讨论】:

      猜你喜欢
      • 2013-12-03
      • 2021-06-10
      • 2013-04-12
      • 2016-09-25
      • 1970-01-01
      • 2015-01-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多