Generate file upload input for property with “DataType.Upload” attribute?

后端 未结 3 1346
野趣味
野趣味 2021-01-07 05:50

I have the following view model.

public class MyViewModel
{
    [DataType(DataType.Upload)]
    public HttpPostedFileBase ImageUpload { get; set; }

    publ         


        
相关标签:
3条回答
  • 2021-01-07 05:59

    How about getting rid of the HttpPostedFileBase from the model and adding it to the controller as a second parameter.

    In your html, you would add:

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

    In your controller you would do:

    [HttpPost]
    public ActionResult thisController(Model myModel, HttpPostedFileBase file)
    { }
    

    This should automatically catch any file you input.

    0 讨论(0)
  • 2021-01-07 06:09

    Change your image control to this,

      @Html.TextBoxFor(m => m.ImageUpload, new { type = "file", name = "Files" })
    
    0 讨论(0)
  • 2021-01-07 06:18

    I have another idea. How about getting rid of the HttpPostedFileBase from the model and from the controller either ?

    In your html, you would add:

     @using (Html.BeginForm("actionNameYouWriteToManupulate", "controllerYouWrite", FormMethod.Post, new { enctype = "multipart/form-data" }))
     {
       <input type="file" name="file" id="File1" />
       <input type="file" name="file" id="File2" />
       ...
       <input type="submit" value="Upload" class="btn btn-info" />
     }
    

    Add Files as many files you want, and in the controller :

    var hfc = Request.Files;
    for (int i = 0; i < hfc.Count; i++)
                {
                    var hpf = hfc[i];
                    if (hpf.ContentLength > 0)
                    {
                       //Do what you want with files 
                       //Handler pointed to file is hpf for example :
                       hpf.SaveAs(Server.MapPath(fullPathWithFileName));
                     }
                }
    

    Hope to be usefull.

    0 讨论(0)
提交回复
热议问题