File Upload as Part of Form with Other Fields

后端 未结 2 1102
南方客
南方客 2021-01-02 08:13

I have an ASP.NET MVC website. I need a page where the user must enter several fields, including an image file.

I could find many, many references for uploading a fi

2条回答
  •  时光取名叫无心
    2021-01-02 08:50

    If you do not use third party libraries, try this:

    Model

    public class Strategy 
        {
            public int ID { get; set; }
            public string Name { get; set; }
            public byte[] File { get; set; }
    
        }
    

    View

     @model TEST.Model.Strategy
     @using (Html.BeginForm("Add", "Strategy", FormMethod.Post, new { @id = "frmStrategy", enctype = "multipart/form-data" }))
            {
                @Html.TextBoxFor(x => x.Name)
                
                @Html.HiddenFor(x => x.ID)
    
            }
    

    Controller

    [HttpPost]
            public ActionResult Add(Strategy model, HttpPostedFileBase templateFile)
            {
    
    
                if (templateFile != null && templateFile.ContentLength > 0)
                {
                    try
                    {
                        var fname = Path.GetFileName(templateFile.FileName);
                        using (MemoryStream ms = new MemoryStream())
                        {
                          templateFile.InputStream.CopyTo(ms);
                          byte[] array = ms.GetBuffer();
                          model.File = array;
                        }
                        ...
    

提交回复
热议问题