MVC3 上傳文件

@model System.Web.HttpContextBase
@{
    ViewBag.Title = "上傳文件";
}

<h2>上傳文件</h2>
<br />
<br />
@*new { enctype = "multipart/form-data" }比不可少,否則上傳文件不會成功 *@
 @using (Html.BeginForm("Upload", "UploadFile", FormMethod.Post, new { enctype = "multipart/form-data" }))
{
    <text>選擇上傳文件:</text><input name="file" type="file" id="file" />
    <br />
    <br />
    <input type="submit" name="Upload" value="Upload" />
}
[HttpPost]
        public ActionResult Upload(FormCollection form)
        {
            if (Request.Files.Count == 0)
            {
      //Request.Files.Count 文件數爲0上傳不成功
      Return View(); 
     }

            var file = Request.Files[0];
            if (file.ContentLength == 0)
            {
                //文件大小大(以字節爲單位)爲0時,做一些操作
      Return View();
     }
     else
    {
      //文件大小不爲0
      HttpPostedFileBase file = Request.Files[0];
      //保存成自己的文件全路徑,newfile就是你上傳後保存的文件,
      //服務器上的UpLoadFile文件夾必須有讀寫權限      
      file.SaveAs(Server.MapPath(@"UploadFile\newfile"));
    }
     
     
      
      newFile = DateTime.Now.ToString("yyyyMMddHHmmss") + ".sl";
            
            return View();

        }

entType屬性說明,摘自http://www.w3school.com.cn/tags/att_form_enctype.asp

在使用時,type=file控件一定要加name屬性,否則報錯,後臺獲不到

定義和用法

enctype 屬性規定在發送到服務器之前應該如何對錶單數據進行編碼。

默認地,表單數據會編碼爲 "application/x-www-form-urlencoded"。就是說,在發送到服務器之前,所有字符都會進行編碼(空格轉換爲 "+" 加號,特殊符號轉換爲 ASCII HEX 值)。

屬性值

描述
application/x-www-form-urlencoded 在發送前編碼所有字符(默認)
multipart/form-data

不對字符編碼。

在使用包含文件上傳控件的表單時,必須使用該值。

text/plain 空格轉換爲 "+" 加號,但不對特殊字符編碼。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章