ASP.NET MVC文件上传简单示例

一. 前端代码

      Form 提交

 @using (Html.BeginForm("UploadFile", "Home", FormMethod.Post, new {enctype = "multipart/form-data"}))
        {
            <div>文件上传:<input type="file" name="myFile"/></div>
            <input type="submit" value="提交"/>
        }

        Ajax 提交 

<div>
    上传文件: <input id="zfiles" type="file" name="myFile" />
    <br />
    <img src=""; style="width:100px;height:100px;" id="imgs" />
    <input type="button" value="上传" onclick="test()" />
</div>

<script>
    function test() {
        var formData = new FormData();
        formData.append("myFile", $('#zfiles')[0].files[0])

        $.ajax({
            url:"@Url.Action("UploadFile", "Home")",
            type: 'POST',
            dataType: 'json',
            data: formData,
            contentType: false,
            processData: false,
            success: function (data) {
                if (data != "") {

                    $("#imgs").attr("src", data);

                }               
            }
        });
    }
</script>

 

 二. 后端代码

        /// <summary>
        /// 上传文件
        /// </summary>
        /// <returns>上传文件结果信息</returns>
        [HttpPost]
        public JsonResult UploadFile()
        {
            HttpPostedFileBase file = Request.Files["myFile"];
            if (file != null)
            {
                try
                {
                    //检查是否存在文件夹
                    string subPath = "D:\\pic";
                    if (false == System.IO.Directory.Exists(subPath))
                    {
                        //创建pic文件夹
                        System.IO.Directory.CreateDirectory(subPath);
                    }                                  
                    var filename = Path.Combine("D:\\pic", file.FileName);  //Path.Combine(Request.MapPath("~/Upload"), file.FileName); MapPath:虚拟目录
                    file.SaveAs(filename);
                    return Json("上传完成");
                }
                catch (Exception ex)
                {
                    return Json(string.Format("上传文件出现异常:{0}", ex.Message));
                }

            }
            else
            {
                return Json("没有文件需要上传!");
            }
        }

 

posted @ 2021-07-02 10:57  一个小伙子  阅读(374)  评论(0编辑  收藏  举报