C#上传文件到WebAPI

  1 上传文件 <input type="file" id="file" />
  2 <input type="button" id="upload" value="上传文件" />
  3 
  4 <script>
  5     //上传
  6     $("#upload").click(function () {
  7         var formData = new FormData();
  8         var file = document.getElementById("file").files[0];
  9         formData.append("fileInfo", file);
 10         $.ajax({
 11             url: "../api/File/UploadFile",
 12             type: "POST",
 13             data: formData,
 14             contentType: false,//必须false才会自动加上正确的Content-Type
 15             processData: false,//必须false才会避开jQuery对 formdata 的默认处理,XMLHttpRequest会对 formdata 进行正确的处理
 16             success: function (data) {
 17                 alert(data);
 18             },
 19             error: function (data) {
 20                 alert("上传失败!");
 21             }
 22         });
 23     });
 24 </script>
 25 
 26 
 27 /// <summary>
 28         /// 上传文件
 29         /// </summary>
 30         [HttpPost]
 31         public string UploadFile()
 32         {
 33             string result = string.Empty;
 34             try
 35             {
 36                 string uploadPath = HttpContext.Current.Server.MapPath("~/App_Data/");
 37                 HttpRequest request = System.Web.HttpContext.Current.Request;
 38                 HttpFileCollection fileCollection = request.Files;
 39                 // 判断是否有文件
 40                 if (fileCollection.Count > 0)
 41                 {
 42                     // 获取文件
 43                     HttpPostedFile httpPostedFile = fileCollection[0];
 44                     string fileExtension = Path.GetExtension(httpPostedFile.FileName);// 文件扩展名
 45                     string fileName = Guid.NewGuid().ToString() + fileExtension;// 名称
 46                     string filePath = uploadPath + httpPostedFile.FileName;// 上传路径
 47                     // 如果目录不存在则要先创建
 48                     if (!Directory.Exists(uploadPath))
 49                     {
 50                         Directory.CreateDirectory(uploadPath);
 51                     }
 52                     // 保存新的文件
 53                     while (File.Exists(filePath))
 54                     {
 55                         fileName = Guid.NewGuid().ToString() + fileExtension;
 56                         filePath = uploadPath + fileName;
 57                     }
 58                     httpPostedFile.SaveAs(filePath);
 59                     result = "上传成功";
 60                 }
 61             }
 62             catch (Exception)
 63             {
 64                 result = "上传失败";
 65             }
 66             return result;
 67         }
 68 
 69 
 70 
 71 <form action="../api/File/DownloadFile" method="get" id="form">
 72    下载文件 <input type="text" id="name" name="fileName" value="222" />
 73 </form>
 74 <input type="button" id="download" value="下载文件" />
 75 
 76 <script>
 77     //下载
 78     $("#download").click(function () {
 79         var form = $("#form");
 80         form.submit();
 81     });
 82 </script>
 83 
 84 
 85 /// <summary>
 86         /// 下载文件
 87         /// </summary>
 88         [HttpGet]
 89         public void DownloadFile()
 90         {
 91             var request = HttpContext.Current.Request;
 92             NameValueCollection nvCollection = request.Params;
 93             string fileName = nvCollection.GetValues("fileName")[0];
 94             string filePath = Path.Combine(HttpContext.Current.Server.MapPath("~/App_Data/"), fileName);
 95             if (File.Exists(filePath))
 96             {
 97                 HttpResponse response = HttpContext.Current.Response;
 98                 response.Clear();
 99                 response.ClearHeaders();
100                 response.ClearContent();
101                 response.Buffer = true;
102                 response.AddHeader("content-disposition", string.Format("attachment; FileName={0}", fileName));
103                 response.Charset = "GB2312";
104                 response.ContentEncoding = Encoding.GetEncoding("GB2312");
105                 response.ContentType = MimeMapping.GetMimeMapping(fileName);
106                 response.WriteFile(filePath);
107                 response.Flush();
108                 response.Close();
109             }
110         }

猜你喜欢

转载自www.cnblogs.com/wmm0105/p/11765280.html