ASP.NET Web API实现简单的文件下载与上传。首先创建一个ASP.NET Web API项目,然后在项目下创建FileRoot目录并在该目录下创建ReportTemplate.xlsx文件,用于下面示例的使用。
1、文件下载
示例:实现报表模板文件下载功能。
1.1 后端代码
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 |
/// <summary> /// 下载文件 /// </summary> [HttpGet] public HttpResponseMessage DownloadFile() { string fileName = "报表模板.xlsx"; string filePath = HttpContext.Current.Server.MapPath("~/") + "FileRoot\\" + "ReportTemplate.xlsx"; FileStream stream = new FileStream(filePath, FileMode.Open); HttpResponseMessage response = new HttpResponseMessage(HttpStatusCode.OK); response.Content = new StreamContent(stream); response.Content.Headers.ContentType = new MediaTypeHeaderValue("application/octet-stream"); response.Content.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment") { FileName = HttpUtility.UrlEncode(fileName) }; response.Headers.Add("Access-Control-Expose-Headers", "FileName"); response.Headers.Add("FileName", HttpUtility.UrlEncode(fileName)); return response; } |
1.2 前端代码
1 |
<a href="http://localhost:51170/api/File/DownloadFile">下载模板</a> |
2、文件上传
示例:实现上传报表文件功能。
2.1 后端代码
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 |
/// <summary> /// 上传文件 /// </summary> [HttpPost] public HttpResponseMessage UploadFile() { try { //获取参数信息 HttpContextBase context = (HttpContextBase)Request.Properties["MS_HttpContext"]; HttpRequestBase request = context.Request; //定义传统request对象 string monthly = request.Form["Monthly"]; //获取请求参数:月度 string reportName = request.Form["ReportName"]; //获取请求参数:报表名称 //保存文件 string fileName = String.Format("{0}_{1}.xlsx", monthly, reportName); string filePath = HttpContext.Current.Server.MapPath("~/") + "FileRoot\\" + fileName; request.Files[0].SaveAs(filePath); //返回结果 var result = new HttpResponseMessage { Content = new StringContent("上传成功", Encoding.GetEncoding("UTF-8"), "application/json") }; return result; } catch (Exception ex) { throw ex; }; } |
2.2 前端代码
1 2 3 4 5 6 |
<form action='http://localhost:51170/api/File/UploadFile' method="post" enctype="multipart/form-data"> 报表月份:<input type="text" name="Monthly" value="2018-11" /><br /> 报表名称:<input type="text" name="ReportName" value="财务报表" /><br /> 报表文件:<input type="file" name="file" /><br /> <input type="submit" value="提交" /> </form> |
from:https://blog.csdn.net/pan_junbiao/article/details/84065952