asp.net mvc 文件上傳,正在投入使用

先引入文中所用的文件,下載地址爲:

https://download.csdn.net/download/xuejunling/10360702

引入兩個js, 一個樣式

View:

@{
    Layout = null;
}

<!DOCTYPE html>

<html>
<head>
    <meta name="viewport" content="width=device-width" />
    <title></title>
    <link rel="stylesheet" href="/layui/css/layui.css" media="all">
    @*<script src="/Scripts/jquery-1.12.4.min.js"></script>*@
    <script src="/Scripts/jquery-1.8.2.min.js"></script>
    <script src="/Scripts/jquery.form.js"></script>
</head>
<body style="margin:0;padding:0;">
    @using (Ajax.BeginForm("UpLoadLogo_Post", "Default",
    new { },
    new AjaxOptions
    {
        HttpMethod = "POST",
        InsertionMode = InsertionMode.Replace,
        AllowCache = false
    }, new { enctype = "multipart/form-data", id = "myForm" }))
    {
        <div class="layui-form-item">
            <div class="layui-inline">
                <div class="layui-input-inline" style="width: 200px;">
                    @Html.TextBox("file", "", new { type = "file", required = "required", multiple = "multiple",style="width:200px;" })
                </div>
                <div class="layui-input-inline" style="width:50px;">
                    <input type="submit" value="上傳" />
                </div>
                <div class="layui-input-inline" style="width:100px;">
                    <div class="bar"></div>
                    <div class="percent" style="padding-top:5px; display:none;">0%</div>
                </div>
            </div>
        </div>
    }
</body>
</html>
<script>
        (function () {
            var bar = $(".bar");
            var percent = $(".percent");
            var status = $("#status");
//以下的js ,加入了上傳進度的判斷, 我在頁面中註釋了,不要這功能了,如果需要 ,可以把上面的隱藏id顯示出來。
            $('form').ajaxForm({
                beforeSend: function () {
                    status.empty();
                    var percentVal = '0%';
                    bar.width(percentVal);
                    percent.html(percentVal);
                },
                uploadProgress: function (event, position, total, percentComplete) {
                    $(".progress").attr("display", "display");
                    var percentVal = percentComplete + '%';
                    bar.width(percentVal);
                    bar.attr("background-color", "#00ff21");
                    percent.html(percentVal);
                },
                success: function (data) {
                    var percentVal = '100%';
                    bar.width(percentVal);
                    percent.attr("background-color", "#00ff21");
                    percent.html(percentVal);
                    if (data && data.Error == "0") {
//此上傳功能可以作爲一個單獨的模塊來使用,在需要有上傳的頁面中加入<iframe>標籤即可。
以下是找到父窗口中的對應的id, 當上傳成功時,向其傳值 。
                        parent.document.getElementById('logo').value = data.Data;
                        parent.document.getElementById('showlogo').innerHTML = "<img src='" + data.Data + "' width='50' height='50' />";
                    } else {
                        parent.document.getElementById('showlogo').innerHTML = data.Message;
                    }
                },
                complete: function (xhr) {
                    $(".progress").attr("display", "none");
                    status.html(xhr.responseText);
                }
            });

        })();
</script>
後臺:
[HttpGet]
        public ActionResult UpLoadLogo(string id)
        {
            return View();
        }

[HttpPost]
        public ActionResult UpLoadLogo_Post()
        {
            if (Request.Files != null && Request.Files.Count > 0)
            {
                float contextlength = 1024 * 1024 * 3;
                float.TryParse(upload_contentlength, out contextlength);
                HttpPostedFileBase file = Request.Files[0];
                if (file.ContentLength == 0)
                {
                    return Json(new { Error = 1, Message = "請選擇上傳的文件!" });
                }
                if (file.ContentLength > contextlength)
                {
                    return Json(new { Error = 1, Message = "上傳文件過大,不能超過" + contextlength / (1024 * 1024 * 1.0) + "M!" });
                }
                string extension = System.IO.Path.GetExtension(file.FileName);
                string oldfilename = Path.GetFileName(file.FileName);

                string now = DateTime.Now.ToString("yyyyMMdd");
                string guid = Guid.NewGuid().ToString("N");
                Random r = new Random();
                int n = r.Next(1000, 9999);
                string newfilename = string.Concat(guid, n, extension);
                string dirpath = string.Format("/{0}/{1}", upload_userlogo, now);
                if (!Directory.Exists(Server.MapPath(dirpath)))
                {
                    Directory.CreateDirectory(Server.MapPath(dirpath));
                }
                string uploadfilepath = Path.Combine(Server.MapPath(dirpath), newfilename);
                file.SaveAs(uploadfilepath);

//IsAllowedExtension判斷文件是否是真實的圖片文件,如果是上傳成功,如果不是,則刪除
//特別提示:爲了安全,服務器的上傳文件夾,一定要去除執行腳本的權限,這樣即使上傳了木馬程序,也不能運行,具體操作,可以網上搜索一下,這裏簡單提供一下如何做,把上傳圖片所在的文件夾裏新建一個web.config文件,裏面寫入以下內容即可。
<?xml version="1.0" encoding="UTF-8"?>
<configuration>
    <system.webServer>
        <handlers accessPolicy="Read" />
    </system.webServer>
</configuration>
以上是小插曲,爲了安全,還是重視點好。
                if (IsAllowedExtension(uploadfilepath))
                {
                    string filepath = dirpath + "/" + newfilename;
                    return Json(new { Error = 0, Data = filepath });
                }
                else
                {

                    if (System.IO.File.Exists(uploadfilepath))
                    {
                        System.IO.File.Delete(uploadfilepath);
                    }
                    return Json(new { Error = 1, Message = "請上傳jpg,png,gif等類型的圖片!" });
                }
            }
            else
            {
                return Json(new { Error = 1, Message = "請選擇要上傳的圖片!" });
            }
        }

//檢測真實圖片格式。
 public static bool IsAllowedExtension(string path)
        {
            System.IO.FileStream fs = new System.IO.FileStream(path, System.IO.FileMode.Open, System.IO.FileAccess.Read);
            System.IO.BinaryReader r = new System.IO.BinaryReader(fs);
            string fileclass = "";
            byte buffer;
            try
            {
                buffer = r.ReadByte();
                fileclass = buffer.ToString();
                buffer = r.ReadByte();
                fileclass += buffer.ToString();

            }
            catch
            {

            }
            r.Close();
            fs.Close();
//說明255216是jpg;7173是gif;6677是BMP,13780是PNG;7790是exe,8297是rar  
            if (fileclass == "255216" || fileclass == "7173" || fileclass == "13780")
            {
                return true;
            }
            else
            {
                return false;
            }

        }

其中:
upload_contentlength :設定的上傳文件的大小。
upload_userlogo: 上傳文件放置的文件夾。

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