upload 2 different files to 2 different destinatio

2019-09-11 16:00发布

问题:

I have a form that I'm posting 2 different files that belongs to 2 different values in my Db table.

Eg. file1=user image , file2=user company logo.

So I need to attach the files url to it's db value with my viewModel, something like this:(Will never work)

    public ActionResult Create(LectureFormViewModel viewModel)
    {
        foreach ((string item in Request.Files).viewModel.Image1)
        {
            //Do
        }
             foreach ((string item in Request.Files).viewModel.Image2)
             {
                 //Do
             }
        var lecture = new Lecture
        {
            Image1 = xxx,
            Image2=yyy,
        }
        _context.LectureGigs.Add(Lecture);
  }

My ViewModel (I have remove parameters )

 public class LectureFormViewModel
 {
    public int Id { get; set; }
    public byte Genre { get; set; }
    public IEnumerable<Genre> Genres { get; set; }

    public string Image1 { get; set; }


    public string Image2 { get; set; }

    public string Action
    {
        get
        {
            Expression<Func<LecController, ActionResult>>
                update = (c => c.Update(this));

            Expression<Func<LecController, ActionResult>>
                create = (c => c.Create(this));

            var action = (Id != 0) ? update : create;
            return (action.Body as MethodCallExpression).Method.Name;
        }

    }
}

The form(View)

@using VoosUpW.Models
@model VoosUpW.ViewModels.LectureFormViewModel

@using (Html.BeginForm(Model.Action, "Lec", FormMethod.Post, new { enctype = "multipart/form-data", @id = "abcdefg" }))

{
    //parm

    <div class="form-group">
        @Html.LabelFor(f => f.Image1)
        <i class="glyphicon glyphicon-folder-open"></i>
        <input id="Image1" name="Image" type="file" class="">
    </div>
    <div class="form-group">
        @Html.LabelFor(f => f.Image2) <i class="glyphicon glyphicon-folder-open"></i>
        <input type="file" name="Image2" class="btn btn-default btn-sm btn-google btn-group-justified hvr-shadow " />
    </div>
        <button type="submit" class="btn btn-primary btn-lg">Save</button>

}

my action header

public ActionResult Create(LectureFormViewModel viewModel)
{

回答1:

You can do this easily with the below code using IEnumerable<HttpPostedFileBase>:

Product:

public class Product
{
  public int ProductId { get; set; }
  public string ProductName { get; set; }
  public string ImagePath1 { get; set; }
  public string ImagePath2 { get; set; }
  public double Price { get; set; }
}

The action:

[HttpPost] 
public ActionResult Upload(Product aProduct, IEnumerable<HttpPostedFileBase> files)
{
    HttpPostedFileBase file1;
    HttpPostedFileBase file2;

    using (var context = new DemoEntities()) //DbContext - Database connection
    {
       file1 = files.ElementAt(0); //Gets the first image
       file2 = files.ElementAt(1); //Gets the second image

       //Take the first and second file
       if (files.ElementAt(0) != null && files.ElementAt(1) != null)
       {
         if (file1 != null && file1.ContentLength > 0 && file2 != null && file2.ContentLength > 0)
         {
           var fileName = System.IO.Path.GetFileName(file1.FileName);
           string path = System.IO.Path.Combine(Server.MapPath("~/Images/"), fileName); //Get the first file path and save to folder

           var fileName2 = System.IO.Path.GetFileName(file2.FileName);
           string path2 = System.IO.Path.Combine(Server.MapPath("~/Images2/"), fileName2);  //Get the second file path and save to folder

           /**In database, followings are being saved - Starts**/
           aProduct.ProductId = 1002;
           aProduct.ImagePath1 = fileName; //Saves the first image file name 
           aProduct.ImagePath2 = fileName2; //Saves the second image file name
           aProduct.ProductName = "Super Product";
           aProduct.Price = 2000;

           try
           {
             context.Products.Add(aProduct); //Save the object and context is the dbContext
             context.SaveChanges();
           }

           catch (Exception ex)
           {
             ex.ToString();
           }
           /**In database, followings are being saved - Ends**/
          }
       }
    }

  return RedirectToAction("Index");
}

Note: Don't worry about image path. For the ease, just save the file name in the Db and finally to display in the view, do the following and for the image upload, the code you showed will work:

<img src="~/Images1/@item.ImagePath1" alt="No Images" class="img">
<img src="~/Images2/@item.ImagePath2" alt="No Images" class="img">