ASP.NET Web API实现简单的文件下载与上传。首先创建一个ASP.NET Web API项目,然后在项目下创建FileRoot目录并在该目录下创建ReportTemplate.xlsx文件,用于下面示例的使用。
1、文件下载
示例:实现报表模板文件下载功能。
1.1 后端代码 - /// <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 前端代码 - <a href="http://localhost:51170/api/File/DownloadFile">下载模板</a>
复制代码
2、文件上传
示例:实现上传报表文件功能。
2.1 后端代码 - /// <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 前端代码 - <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>
复制代码
来源:https://blog.csdn.net/pan_junbiao/article/details/84065952 免责声明:如果侵犯了您的权益,请联系站长,我们会及时删除侵权内容,谢谢合作! |