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

本文介绍如何使用ASP.NET WebAPI实现文件的上传和下载功能。包括后端代码实现和前端页面调用,适用于报表模板等文件的管理和操作。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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>

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

pan_junbiao

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

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

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

打赏作者

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

抵扣说明:

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

余额充值