WebAPI的文件上传与下载

 上传:

 

<input type="file" id="file" />
<input type="button" id="upload" value="上传文件" />

<script>
    //上传
    $("#upload").click(function () {
        var formData = new FormData();
        var file = document.getElementById("file").files[0];
        formData.append("fileInfo", file);
        $.ajax({
            url: "../api/File/UploadFile",
            type: "POST",
            data: formData,
            contentType: false,//必须false才会自动加上正确的Content-Type
            processData: false,//必须false才会避开jQuery对 formdata 的默认处理,XMLHttpRequest会对 formdata 进行正确的处理
            success: function (data) {
                alert(data);
            },
            error: function (data) {
                alert("上传失败!");
            }
        });
    });
</script>

 

/// <summary>
        /// 上传文件
        /// </summary>
        [HttpPost]
        public string UploadFile()
        {
            string result = string.Empty;
            try
            {
                string uploadPath = HttpContext.Current.Server.MapPath("~/App_Data/");
                HttpRequest request = System.Web.HttpContext.Current.Request;
                HttpFileCollection fileCollection = request.Files;
                // 判断是否有文件
                if (fileCollection.Count > 0)
                {
                    // 获取文件
                    HttpPostedFile httpPostedFile = fileCollection[0];
                    string fileExtension = Path.GetExtension(httpPostedFile.FileName);// 文件扩展名
                    string fileName = Guid.NewGuid().ToString() + fileExtension;// 名称
                    string filePath = uploadPath + httpPostedFile.FileName;// 上传路径
                    // 如果目录不存在则要先创建
                    if (!Directory.Exists(uploadPath))
                    {
                        Directory.CreateDirectory(uploadPath);
                    }
                    // 保存新的文件
                    while (File.Exists(filePath))
                    {
                        fileName = Guid.NewGuid().ToString() + fileExtension;
                        filePath = uploadPath + fileName;
                    }
                    httpPostedFile.SaveAs(filePath);
                    result = "上传成功";
                }
            }
            catch (Exception)
            {
                result = "上传失败";
            }
            return result;
        }

 下载:

 

<form action="../api/File/DownloadFile" method="get" id="form">
   下载文件 <input type="text" id="name" name="fileName" value="222" />
</form>
<input type="button" id="download" value="下载文件" />

<script>
    //下载
    $("#download").click(function () {
        var form = $("#form");
        form.submit();
    });
</script>

 

/// <summary>
        /// 下载文件
        /// </summary>
        [HttpGet]
        public void DownloadFile()
        {
            var request = HttpContext.Current.Request;
            NameValueCollection nvCollection = request.Params;
            string fileName = nvCollection.GetValues("fileName")[0];
            string filePath = Path.Combine(HttpContext.Current.Server.MapPath("~/App_Data/"), fileName);
            if (File.Exists(filePath))
            {
                HttpResponse response = HttpContext.Current.Response;
                response.Clear();
                response.ClearHeaders();
                response.ClearContent();
                response.Buffer = true;
                response.AddHeader("content-disposition", string.Format("attachment; FileName={0}", fileName));
                response.Charset = "GB2312";
                response.ContentEncoding = Encoding.GetEncoding("GB2312");
                response.ContentType = MimeMapping.GetMimeMapping(fileName);
                response.WriteFile(filePath);
                response.Flush();
                response.Close();
            }
        }

 

posted on 2018-12-28 14:29  TheHeist  阅读(522)  评论(0编辑  收藏  举报