.net core webapi导出文件

5 篇文章 1 订阅

.net core webapi导出文件,支持windows系统和liunx系统使用k8s挂载方式

[HttpGet("/DownFile")]
        [ProducesResponseType(StatusCodes.Status500InternalServerError)]
        [ProducesResponseType(typeof(FileResult), StatusCodes.Status200OK)]
        public Task<FileResult> DownFile(string Path,string FileName)
        {
            try
            {
                string path = Path.Combine(Path, FileName);
                if (!System.IO.File.Exists(path))
                {
                    Console.WriteLine("没有找到文件");
                }
                FileStream stream = System.IO.File.OpenRead(path);
                //导出的是excel文件所以使用application/x-xls,其他文件格式参考(https://editor.csdn.net/md/?articleId=107837283)
                var data = new FileStreamResult(stream, new Microsoft.Net.Http.Headers.MediaTypeHeaderValue("application/x-xls"));
                data.FileDownloadName =FileName;
                return Task.FromResult<FileResult> (data);
            }
            catch(Exception ex)
            {
                Console.WriteLine(ex.Message);
                return Task.FromResult<FileResult>(null);
            }
        }

swagger中查看
在这里插入图片描述

  • 2
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
.NET Core WebAPI 可以通过以下步骤实现文件上传: 1. 在 WebAPI 控制器中添加一个方法,该方法接收一个 IFormFile 类型的参数,用于接收上传的文件。 2. 在方法中使用 IFormFile.SaveAsAsync() 方法将文件保存到指定的位置。 3. 在 WebAPI 的 Startup.cs 文件中添加以下代码,以启用文件上传功能: ```csharp services.AddMvc(options => { options.Filters.Add(new ConsumesAttribute("multipart/form-data")); options.Filters.Add(new ProducesAttribute("application/json")); }).AddJsonOptions(options => { options.SerializerSettings.ContractResolver = new CamelCasePropertyNamesContractResolver(); }); services.Configure<IISServerOptions>(options => { options.AllowSynchronousIO = true; }); services.Configure<FormOptions>(options => { options.MemoryBufferThreshold = int.MaxValue; options.ValueLengthLimit = int.MaxValue; options.MultipartBodyLengthLimit = int.MaxValue; }); ``` 4. 在 WebAPI 的控制器方法中使用 [FromForm] 属性将上传的文件绑定到方法参数中。 例如: ```csharp [HttpPost] public async Task<IActionResult> UploadFile([FromForm] IFormFile file) { if (file == null || file.Length == 0) { return BadRequest("File is empty."); } var filePath = Path.Combine(_environment.ContentRootPath, "uploads", file.FileName); using (var stream = new FileStream(filePath, FileMode.Create)) { await file.CopyToAsync(stream); } return Ok("File uploaded successfully."); } ``` 以上就是 .NET Core WebAPI 上传文件的基本步骤。

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值