WebApi实现单个文件的上传下载

2021-06-29 10:08

阅读:615

标签:href   nload   分享   nbsp   create   process   control   gui   success   

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

一、上传功能

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

三、遇到的问题

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

WebApi实现单个文件的上传下载

标签:href   nload   分享   nbsp   create   process   control   gui   success   

原文地址:https://www.cnblogs.com/LikeHeart/p/9581878.html


评论


亲,登录后才可以留言!