zoukankan      html  css  js  c++  java
  • WebApi实现单个文件的上传下载

    上传和下载是很常用的功能了,只有当用到的时候才发现不会写...,经过一番百度、筛选、整理修改后,实现了功能,下面简单的记录下实现方法。

    一、上传功能

    1.前端代码

    上传文件 <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>

    2.后台代码

     1         /// <summary>
     2         /// 上传文件
     3         /// </summary>
     4         [HttpPost]
     5         public string UploadFile()
     6         {
     7             string result = string.Empty;
     8             try
     9             {
    10                 string uploadPath = HttpContext.Current.Server.MapPath("~/App_Data/");
    11                 HttpRequest request = System.Web.HttpContext.Current.Request;
    12                 HttpFileCollection fileCollection = request.Files;
    13                 // 判断是否有文件
    14                 if (fileCollection.Count > 0)
    15                 {
    16                     // 获取文件
    17                     HttpPostedFile httpPostedFile = fileCollection[0];
    18                     string fileExtension = Path.GetExtension(httpPostedFile.FileName);// 文件扩展名
    19                     string fileName = Guid.NewGuid().ToString() + fileExtension;// 名称
    20                     string filePath = uploadPath + httpPostedFile.FileName;// 上传路径
    21                     // 如果目录不存在则要先创建
    22                     if (!Directory.Exists(uploadPath))
    23                     {
    24                         Directory.CreateDirectory(uploadPath);
    25                     }
    26                     // 保存新的文件
    27                     while (File.Exists(filePath))
    28                     {
    29                         fileName = Guid.NewGuid().ToString() + fileExtension;
    30                         filePath = uploadPath + fileName;
    31                     }
    32                     httpPostedFile.SaveAs(filePath);
    33                     result = "上传成功";
    34                 }
    35             }
    36             catch (Exception)
    37             {
    38                 result = "上传失败";
    39             }
    40             return result;
    41         }

    二、下载功能

    1.前端代码

     1 <form action="../api/File/DownloadFile" method="get" id="form">
     2    下载文件 <input type="text" id="name" name="fileName" value="222" />
     3 </form>
     4 <input type="button" id="download" value="下载文件" />
     5 
     6 <script>
     7     //下载
     8     $("#download").click(function () {
     9         var form = $("#form");
    10         form.submit();
    11     });
    12 </script>

    2.后台代码

     1         /// <summary>
     2         /// 下载文件
     3         /// </summary>
     4         [HttpGet]
     5         public void DownloadFile()
     6         {
     7             var request = HttpContext.Current.Request;
     8             NameValueCollection nvCollection = request.Params;
     9             string fileName = nvCollection.GetValues("fileName")[0];
    10             string filePath = Path.Combine(HttpContext.Current.Server.MapPath("~/App_Data/"), fileName);
    11             if (File.Exists(filePath))
    12             {
    13                 HttpResponse response = HttpContext.Current.Response;
    14                 response.Clear();
    15                 response.ClearHeaders();
    16                 response.ClearContent();
    17                 response.Buffer = true;
    18                 response.AddHeader("content-disposition", string.Format("attachment; FileName={0}", fileName));
    19                 response.Charset = "GB2312";
    20                 response.ContentEncoding = Encoding.GetEncoding("GB2312");
    21                 response.ContentType = MimeMapping.GetMimeMapping(fileName);
    22                 response.WriteFile(filePath);
    23                 response.Flush();
    24                 response.Close();
    25             }
    26         }

    三、遇到的问题

    1.写了个测试的html页,如何让程序运行时打开这个页面,在默认执行的HomeControler中添加重定向代码

    HttpContext.Response.Redirect("Html/Index.html", true);

     2.跨域问题

    当问题1中html页和后端程序分开部署时,就会产生跨域问题

    可在web.config中进行如下配置

    1   <system.webServer>
    2     <httpProtocol>
    3       <customHeaders>
    4         <add name="Access-Control-Allow-Origin" value="*"/>
    5         <add name="Access-Control-Allow-Headers" value="X-Requested-With,Content-Type,Accept,Origin"/>
    6         <add name="Access-Control-Allow-Methods" value="GET,POST,PUT,DELETE,OPTIONS"/>
    7       </customHeaders>    
    8     </httpProtocol>
    9   </system.webServer>

    详情可阅读:https://www.cnblogs.com/landeanfen/p/5177176.html

    Demo下载:https://pan.baidu.com/s/1zV1-4WvrP3ZTWwTDFAmExQ

  • 相关阅读:
    bzoj 1176 cdq分治套树状数组
    Codeforces 669E cdq分治
    Codeforces 1101D 点分治
    Codeforces 1100E 拓扑排序
    Codeforces 1188D Make Equal DP
    Codeforces 1188A 构造
    Codeforces 1188B 式子转化
    Codeforces 1188C DP 鸽巢原理
    Codeforces 1179D 树形DP 斜率优化
    git commit -m "XX"报错 pre -commit hook failed (add --no-verify to bypass)问题
  • 原文地址:https://www.cnblogs.com/LikeHeart/p/9581878.html
Copyright © 2011-2022 走看看