3月 31, 2014

MVC 檔案上傳fileupload

Protected Sub Button4_Click(ByVal sender As Object, ByVal e As System.EventArgs)
        Try

            
            Dim a2 As FileUpload = FormView1.FindControl("FileUpload2")
            a2.SaveAs(Server.MapPath("./upload/") + a2.FileName)

            Dim c2 As Label = FormView1.FindControl("Label444")
            c2.Text = a2.FileName
            a2.Enabled = False

            Dim d2 As Button = FormView1.FindControl("Button4")
            d2.Enabled = False
            Label2.Text = "上傳成功!!"
        Catch ex As Exception
            Label2.Text = ex.ToString()
        End Try
    End Sub
首先在VIEW中輸入程式碼:
<form action="@Url.Action("MultiUpload")" method="post" enctype="multipart/form-data">
    <input id="File1" type="file" name="files"/>
    <input id="File2" type="file" name="files"/>
    <input id="Submit1" type="submit" value="submit" />
    <input id="Reset2" type="reset" value="reset" />
</form>
接著是controll中的files必須對應到input的tag中的name即可
[HttpPost]
        public ActionResult MultiUpload(IEnumerable<HttpPostedFileBase> files)
        {
            foreach (var file in files)
            {
                if (file != null && file.ContentLength > 0)
                {
                    
                    var path = Server.MapPath("~/App_Data/") + file.FileName;
                    file.SaveAs(path);
                }
            }
            return RedirectToAction("Index");
            
        }

沒有留言: