简体   繁体   English

如何在 web API 的响应中附加文件

[英]how to attach a file in a response from web API

I need to generate a Excel file in my webAPI in ASP.NET Core with the data received from a aurelia web app.我需要使用从 aurelia web 应用程序接收的数据在 ASP.NET Core 的 webAPI 中生成 Excel 文件。 The flow is this: In frontend I make the request流程是这样的:在前端我提出请求

Print(printData: PrintData) {
return this.http
  .fetch(`planning/Print`, {
    method: "post",
    body: json(printData)
  })
  .then(response => response.json())
  .catch(error => {
    console.log(error);
  });

} }

In web API Controller I get the data and generate the Excel file using the ClosedXML library在 web API Controller 中,我获取数据并生成 ZC1D81AF5835844B4E9E936d910DED8 文件

[HttpPost]
[Route("Print")]
public async Task<IActionResult> Print([FromBody] PrintDataVM data)
{      

  var getResponse = await mediator.Send(new PrintPlanning(data));

  return Ok(getResponse);

public async Task<XLWorkbook> PrintPlanning(PrintDataVM data)
  {
    using (XLWorkbook workBook=new XLWorkbook())
    {
      var workSheet= workBook.Worksheets.Add("Horas");

       workSheet.Cell("A1").Value = "Hola";

      return workBook;    
    }

In my controller getResponse is this在我的 controller getResponse 是这个得到响应

得到响应

and here my doubts begin because I don't know if I should get this obtejct or a memorystream.在这里我开始怀疑,因为我不知道我是否应该得到这个对象或内存流。 I do not know how to make the frontend get this so that once received I can treat it there.我不知道如何让前端得到这个,以便一旦收到我就可以在那里处理它。 Right now this gives me error obviously现在这显然给了我错误

Any idea please?请问有什么想法吗?

Regards问候

错误提取

Save your file to stream and return file将文件保存到 stream 并返回文件

var getResponse = await mediator.Send(new PrintPlanning(data));

var ms = new MemoryStream();
getResponse.SaveAs(ms);
ms.Position = 0;
return File(ms, "application/octet-stream", "filename");

or use application/vnd.openxmlformats-officedocument.spreadsheetml.sheet instead of application/octet-stream或使用application/vnd.openxmlformats-officedocument.spreadsheetml.sheet而不是application/octet-stream

You can use this extension to simplify things: https://www.nuget.org/packages/ClosedXML.Extensions.WebApi/你可以使用这个扩展来简化事情: https://www.nuget.org/packages/ClosedXML.Extensions.WebApi/

Usage用法

In your WebApi controller define an action that will generate and download your file:在您的 WebApi controller 中定义将生成和下载文件的操作:

public class ExcelController : ApiController
{
    [HttpGet]
    [Route("api/file/{id}")]
    public async Task<HttpResponseMessage> DownloadFile(int id)
    {
        var wb = await BuildExcelFile(id);
        return wb.Deliver("excelfile.xlsx");
    }

    private async Task<XLWorkbook> BuildExcelFile(int id)
    {
        //Creating the workbook
        var t = Task.Run(() =>
        {
            var wb = new XLWorkbook();
            var ws = wb.AddWorksheet("Sheet1");
            ws.FirstCell().SetValue(id);

            return wb;
        });

        return await t;
    }
}

Disclaimer: I'm the author.免责声明:我是作者。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM