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>

 

  • 1
    点赞
  • 38
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
以下是使用 ASP.NET Web API 实现文件下载的教程: 1. 创建 Web API 项目 首先,你需要创建一个 ASP.NET Web API 项目。在 Visual Studio 中选择 File -> New -> Project,然后选择 ASP.NET Web Application,选择 Web API 项目模板并命名项目。 2. 添加文件下载方法 在 Web API 项目中,你需要添加一个方法来处理文件下载请求。你可以在控制器类中添加以下方法: ```csharp public HttpResponseMessage GetFile(string fileName) { var filePath = HttpContext.Current.Server.MapPath("~/App_Data/" + fileName); if (!File.Exists(filePath)) { return Request.CreateErrorResponse(HttpStatusCode.NotFound, "File not found."); } var fileBytes = File.ReadAllBytes(filePath); var response = new HttpResponseMessage(HttpStatusCode.OK) { Content = new ByteArrayContent(fileBytes) }; response.Content.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment") { FileName = fileName }; response.Content.Headers.ContentType = new MediaTypeHeaderValue("application/octet-stream"); response.Content.Headers.ContentLength = fileBytes.LongLength; return response; } ``` 在上面的方法中,我们首先检查请求的文件是否存在,如果不存在,则返回“File not found”的错误响应。如果文件存在,则读取文件的字节数组,并将其作为响应的内容。我们还设置了响应头的 Content-Disposition 和 Content-Type,以指示浏览器将文件下载到本地计算机。 3. 添加路由 接下来,你需要为文件下载方法添加路由。在 WebApiConfig 类中添加以下代码: ```csharp config.Routes.MapHttpRoute( name: "DownloadFile", routeTemplate: "api/files/{fileName}", defaults: new { controller = "files", action = "GetFile" } ); ``` 此路由将匹配形如“api/files/{fileName}”的 URL,并将其路由到 GetFile 方法。 4. 测试文件下载 现在,你可以启动 Web API 项目,并使用类似以下的 URL 来测试文件下载: ``` http://localhost:port/api/files/your_file_name.txt ``` 此 URL 将下载位于 App_Data 文件夹中的“your_file_name.txt”文件。 就是这样,你现在已经知道了如何使用 ASP.NET Web API 实现文件下载

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

pan_junbiao

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值