松鼠的博客

导航

ASP.NET Web API实现简单的文件下载与上传

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>

 

参考文章:http://blog.ncmem.com/wordpress/2023/12/07/asp-net-web-api%e5%ae%9e%e7%8e%b0%e7%ae%80%e5%8d%95%e7%9a%84%e6%96%87%e4%bb%b6%e4%b8%8b%e8%bd%bd%e4%b8%8e%e4%b8%8a%e4%bc%a0/

欢迎入群一起讨论

 

 

posted on 2023-12-07 11:54  Xproer-松鼠  阅读(169)  评论(0编辑  收藏  举报