關於MVC 上傳檔案

來源:互聯網
上載者:User

標籤:style   blog   http   color   java   os   io   檔案   

 前台代碼如下

@{    Layout = null;}<!DOCTYPE html><html><head>    <title>Index</title>    <script src="@Url.Content("~/Scripts/jquery-1.5.1.min.js")" type="text/javascript"></script>    <script type="text/javascript">        var times = 1;        $("#add").click(function () {            var fileNmae = "FileUpLoad" + n;            $("#divdivfile").append("<input type=\"file\" name=\"" + fileNmae + "\" />");            times++;        });    </script></head><body>    <div>        @using (Html.BeginForm("UpLoad", "UpdateLoad", FormMethod.Post, new { enctype="mutipart/form-data"}))        {             <div id="divfile">                <input type="file" name="FileUpload" />            </div>            <input type="button" id="add" value="增加" />            <input type="submit" id="Submit" value="上傳" />        }    </div></body></html>

首先判斷上傳的檔案是否合法

    public enum FileTypeExtension    {        GIF = 7173,        PNG = 13780,        JPG = 255216,    }    public class FileUploadCommon    {        /// <summary>        /// 主要用於判斷上傳的特定檔案是否附合特定尾碼名的限制        /// </summary>        /// <param name="fu">上傳的檔案對象</param>        /// <param name="fileEx">系統允許上傳的檔案的類型</param>        /// <returns>true:代表通過驗證,false:代表沒有通過驗證</returns>        public static bool IsAllowedExtension(HttpPostedFileBase fu, FileTypeExtension[] fileEx)        {            int contentLength = fu.ContentLength;            byte[] buffer = new byte[contentLength];            fu.InputStream.Read(buffer, 0, contentLength);            MemoryStream input = new MemoryStream(buffer);            BinaryReader reader = new BinaryReader(input);            string s = "";            try            {                s = reader.ReadByte().ToString();                s = s + reader.ReadByte().ToString();            }            catch            {            }            reader.Close();            input.Close();            foreach (FileTypeExtension extension in fileEx)            {                if (int.Parse(s) == Convert.ToInt32(extension))                {                    return true;                }            }            return false;        }    }

 

後台代碼 分為 單個上傳和批量上傳,注示部份為批量上傳

[HttpPost]        [ValidateInput(false)]        public ActionResult UpLoad(FormModel model)        {            FileTypeExtension[] fileTypeArr = { FileTypeExtension.GIF, FileTypeExtension.JPG, FileTypeExtension.PNG };            // 單個上傳            try            {                if (Request.Files != null && Request.Files.Count > 0 && Request.Files[0].ContentLength > 0)                {                    string fileType = Request.Files[0].ContentType;   // 擷取檔案類型                    Stream fileStream = Request.Files[0].InputStream;                    bool fileOk = FileUploadCommon.IsAllowedExtension(Request.Files[0], fileTypeArr);    // 判斷上傳的檔案是否合法                    if (fileOk && Request.Files[0].ContentLength / 1024 < 1024)   // 判斷合法 及 檔案大小是否合法                    {                        string path = Server.MapPath("/Content/FileUpdateLoad/");                        string fileName = Path.GetFileNameWithoutExtension(Request.Files[0].FileName) + DateTime.Now.ToString("yyyyMMddHHmmss") + fileType;                        Request.Files[0].SaveAs(Path.Combine(path, fileName));                        return RedirectToAction("Index", "UpdateLoad");
}
else ViewBag.Error = "檔案過大或格式不正確"; } else ViewBag.Error = "上傳檔案失敗,可能您未選擇上傳檔案"; } catch (Exception ex) { ViewBag.Error = "上傳檔案失敗,原因如下:" + ex.Message; } //foreach (string upload in Request.Files) // 如果是批量上傳 //{ // if (upload != null && Request.Files[upload].ContentLength > 0) // { // string fileType = Request.Files[upload].ContentType; // 擷取檔案類型 // Stream fileStream = Request.Files[upload].InputStream; // bool fileOk = FileUploadCommon.IsAllowedExtension(Request.Files[upload], fileTypeArr); // 判斷上傳的檔案是否合法 // if (fileOk && Request.Files[upload].ContentLength / 1024 < 1024) // 判斷合法 及 檔案大小是否合法 // { // string path = Server.MapPath("/Content/FileUpdateLoad/"); // string fileName = Path.GetFileNameWithoutExtension(Request.Files[upload].FileName) + DateTime.Now.ToString("yyyyMMddHHmmss") + fileType; // Request.Files[upload].SaveAs(Path.Combine(path, fileName)); // } // else // ViewBag.Error = "檔案過大或格式不正確"; // } // else continue; //} return View(model);
}

 

 

關於設定檔 限制上傳檔案大小 和上傳時間

    <httpRuntime executionTimeout="5000" maxRequestLength="2048000" useFullyQualifiedRedirectUrl="false"/>  </system.web>

 

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.