ASP.NET MVC+ajax实现文件上传及文件下载

文件上传:

视图 view:

@{
    ViewBag.Title = "Index";
}
  
<h2>文件管理</h2>
<form enctype="multipart/form-data">
    <input id="F1" type="file" />
    <input id="Button1" type="button" value="上传" onclick="upload()" />
</form>
<script>
    function upload() {
        var data = new FormData();
        //获取文件
        var file = document.getElementById("F1").files[0];
        //添加数据
        data.append("F1", file);
        $.ajax({
            url: '/File/Upload/',
            type: 'post',
            data: data,
            contentType: false,//必须false才会自动加上正确的Content-Type
            processData: false,//必须false才会避开jQuery对 formdata 的默认处理,XMLHttpRequest会对 formdata 进行正确的处理
            success: function (d) {
                if (d>0) {
                    alert("上传成功!");
                    return;
                } else {
                    alert("上传失败!");
                    return;
                }
            }
        });
    }
</script>
 
 
控制器 controller
public ActionResult Index()
        {
            return View();
        }
        /// <summary>
        /// 文件上传
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public int Upload()
        {
            //判断文件是否选中
            if (Request.Files.Count>0)
            {
                //获取文件
                var file = HttpContext.Request.Files[0];
                //获取上传文件的扩展名
                //首先将文件名按.切割
                var temp = file.FileName.Split('.');
                //获取扩展名
                var extendName = temp[temp.Length - 1];
                //获取路径
                var path = HttpContext.Server.MapPath("~/Upload/");
                //判断路径是否存在
                if (Directory.Exists(path))
                {
                    Directory.CreateDirectory(path);
                }
                //文件重新命名
                var name = DateTime.Now.ToFileTime() + "." + extendName;
                //保存上传文件
                file.SaveAs(Path.Combine(path, name));
                //返回结果
                return 1;
            }
            else
            {
                return 0;
            }
        }
 
文件下载:
 
视图 view:
<a href='@Url.Action("Download","File",new { fileName=item.FName})'>下载文件</a>
 
控制器 contorller:
/// <summary>
        /// 下载文件
        /// </summary>
        /// <param name="fileName"></param>
        /// <returns></returns>
        public FileStreamResult Download(string fileName)
        {
            string filePath = Server.MapPath(string.Format("~/{0}/{1}", "Upload", fileName));
            FileStream fs = new FileStream(filePath, FileMode.Open);
            return File(fs, "text/plain", fileName);
        }
 
 
原文地址:https://www.cnblogs.com/sxkang/p/13361068.html