ASP.NET MVC上傳文件

ASP.NET MVC上傳文件

1.視圖顯示

	        <form action="Upload" method="post" enctype="multipart/form-data">
            <table>
                <tr>
                    <td><input type="file" name="file" value="" /></td>
                    <td><input type="submit" name="upload" value="上傳" /></td>
                </tr>
            </table>
        </form>

2.接收文件上傳數據

利用方法參數映射功能,直接將文件映射爲HttpPostedFileBase類型,該類型是抽象類,包含成員

屬性或方法 說明
int ContentLength{get;} 獲取上載的文件大小
string ContentType{get;} 獲取上載的文件的MIME內容類型
string FileName{get;} 獲取客戶端上文件的完全限定名
Stream InputStream{get;} 獲取Stream對象,該對象指向一個上載文件
void SaveAs(string fname) 保存上載文件的內容

MIME類型就是設定某種擴展名的文件用一種應用程序來打開的方式類型,當擴展名文件被訪問的時候,瀏覽器會自動使用指定應用程序來打開。

 [HttpPost]
        public ActionResult Upload(HttpPostedFileBase file)
        {
            if (file != null)
            {
                string path = Server.MapPath("~/File/") + file.FileName;
                file.SaveAs(path);
                return Content("<script>alert('上傳文件成功!');location.herf="+Url.Content("~/FileUpload")+"</script>");
            }
            else
            {
                return View("FileUpload");
            }
        }
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章