• 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         }
  • 相关阅读:
    maven解决“Could not calculate build plan”问题
    HTTP中的重定向和请求转发的区别
    (转)《杂 文》 之 教你制作一份属于自己的简历
    (转)《SSO CAS单点系列》之 实现一个SSO认证服务器是这样的!
    (转)《SSO CAS单点系列》之 15分钟让你了解SSO技术到底是个什么鬼!
    (转)帮你深入理解OAuth2.0协议
    opengl库区分:glut、freeglut、glfw、glew、gl3w、glad
    OpenGL中的光照技术(翻译)
    [转]gluProject 和 gluUnproject 的详解
    英文版Ubuntu18.10安装搜狗输入法过程(图文并茂,亲自尝试!)
  • 原文地址:https://www.cnblogs.com/wmm0105/p/11765280.html
Copyright © 2020-2023  润新知