1. 程式人生 > >點選按鈕,自動瀏覽檔案,選好檔案之後自動上傳

點選按鈕,自動瀏覽檔案,選好檔案之後自動上傳

上傳功能在前端應用中經常用到,現在網上很多上傳的外掛,在之前的博文中介紹一個 fileinput外掛,下面就使用簡單的input實現檔案上傳

先看效果:

 前臺程式碼:

<h2>使用input標籤上傳</h2>
<div>
    <input type="file"  style="display:none" onchange="Upload()" id="FileUpload"/><input  type="button" value="瀏覽檔案選擇檔案自動提交" onclick=" OpenFile()" class="btn btn-info"/>
</div>
<script>
    function OpenFile() {
        $("input[type='file' ]").click();
    }
    function Upload() {
        var fileObj = document.getElementById("FileUpload").files[0]; // js 獲取檔案物件
        if (typeof (fileObj) == "undefined" || fileObj.size <= 0) {
            alert("請選擇檔案")
            return;
        }
        var files = $("#FileUpload").val();
        var ex = files.substring(files.indexOf('.'), files.length).toUpperCase();
        if (ex== ".JPG" || ex== ".PNG"||ex == ".GIF") {
            var formFile = new FormData();
            formFile.append("action", "UploadVMKImagePath");
            formFile.append("file", fileObj); //加入檔案物件
            var data = formFile;
            $.ajax({
                url: "/Test/Upload",
                data: data,
                type: "Post",
                dataType: "json",
                cache: false,//上傳檔案無需快取
                processData: false,//用於對data引數進行序列化處理 這裡必須false
                contentType: false, //必須
                success: function (result) {
                    if (result.Return) {
                        alert("上傳成功")
                    } else {
                        alert(result.Message)
                    }
                }, error: function (ex) {
                    console.warn(ex)
                }
            })
        } else {
            alert("檔案格式不符")        
        }
    }
</script>

後臺程式碼

 public JsonResult Upload()
        {
            string directoryPath = Server.MapPath("../Content/ModelFolder");
            string Img = Server.MapPath("../Content/Img");
            if (!Directory.Exists(directoryPath))
                Directory.CreateDirectory(directoryPath);
            try
            {
                foreach (string f in Request.Files)
                {
                    HttpPostedFileBase file = Request.Files[f];
                    if (file != null && file.ContentLength > 0)
                    {
                        string fileName = file.FileName;
                        string filePath = Path.Combine(directoryPath, fileName);
                        file.SaveAs(filePath);//儲存上傳的檔案
                    }
                }
                return Json(new { Return = true });
            }
            catch (Exception ex)
            {
                return Json(new { Return = false, Message = ex.Message });
            }
        }