简体   繁体   English

如何从web api控制器返回文件?

[英]How to return a file from web api controller?

I'm using a MVC 5 web Api Controller, and I want to return a file: 我正在使用MVC 5 web Api Controller,我想返回一个文件:

[Route("")]
public HttpResponseMessage GetFile()
{
    var statusCode = HttpStatusCode.OK;
    FileStream file = XLGeneration.XLGeneration.getXLFileExigence();

    return Request.CreateResponse(statusCode, file);
}

It dosn't work. 它不起作用。

The exception from postman is: 邮递员的例外是:

"ExceptionMessage": "The 'ObjectContent`1' type failed to serialize the response body for content type 'application/json; charset=utf-8'." “ExceptionMessage”:“'ObjectContent`1'类型无法序列化内容类型'application / json; charset = utf-8'的响应主体。”

I'm posting what worked for me as an alternative in case anybody else is having trouble. 我发布了对我有用的东西,以防其他人遇到麻烦。

[ActionName("File")]
[HttpGet]
public HttpResponseMessage File()
{
        var response = new HttpResponseMessage(HttpStatusCode.OK);
        var stream = new System.IO.FileStream(yourFilePath, System.IO.FileMode.Open);
        response.Content = new StreamContent(stream);
        response.Content.Headers.ContentType = new System.Net.Http.Headers.MediaTypeHeaderValue("application/octet-stream");

        return response;
}

I returned byte[] from WebAPI controller and download PDF successfully. 我从WebAPI控制器返回了byte []并成功下载了PDF。 I'm using iTextSharp (LGPL) 4.1.6 free PDF converter. 我正在使用iTextSharp(LGPL)4.1.6免费PDF转换器。 To install iTextSharp (LGPL / MPL), run the following command in the Package Manager Console. 要安装iTextSharp(LGPL / MPL),请在程序包管理器控制台中运行以下命令。

Install-Package iTextSharp-LGPL -Version 4.1.6 安装包iTextSharp-LGPL -Version 4.1.6

Server side code 服务器端代码

    [Route("Export/ExportToPdf")]

    public byte[] ExportToPdf(string html)
    {           

        MemoryStream msOutput = new MemoryStream();
        TextReader reader = new StringReader(html);
        Document document = new Document(new Rectangle(842, 595));             
        PdfWriter writer = PdfWriter.GetInstance(document, msOutput);
        document.Open();
        document.HtmlStyleClass = @"<style>*{ font-size: 8pt; font-family:arial;}</style>";

        var parsedHtmlElements = HTMLWorker.ParseToList(new StringReader(html), null);
        foreach (var htmlElement in parsedHtmlElements)
        {
            document.Add(htmlElement as IElement);
        }

        document.Close();

        return msOutput.ToArray();
    }

Client Side Code. 客户端代码。

//Call this function inside of AJAX success.
function ExportToPDF(data) {

    //base64 To ArrayBuffer
    var binaryString = window.atob(data);
    var binaryLen = binaryString.length;
    var bytes = new Uint8Array(binaryLen);
    for (var i = 0; i < binaryLen; i++) {
        var ascii = binaryString.charCodeAt(i);
        bytes[i] = ascii;
    }
    //-------

    var link = document.createElement('a');
    link.href = window.URL.createObjectURL(new Blob([bytes], { type: 'application/pdf' }));
    link.download = "Report.pdf";
    link.click();   
}

Try this... 尝试这个...

[Route("")]
public HttpResponseMessage GetFile()
{
    var result = new HttpResponseMessage(HttpStatusCode.OK);
    try
    {
        var file = XLGeneration.XLGeneration.getXLFileExigence();
        result.Content = new StreamContent(file);
        result.Content.Headers.ContentType = new System.Net.Http.Headers.MediaTypeHeaderValue("application/octet-stream");
        var value = new System.Net.Http.Headers.ContentDispositionHeaderValue("attachment");
        value.FileName = "Whatever your filename is";
        result.Content.Headers.ContentDisposition = value;
    }
    catch (Exception ex)
    {
        // log your exception details here
        result = new HttpResponseMessage(HttpStatusCode.InternalServerError);
    }
    return result;
}

This should actually stream it back as a file. 这应该实际上作为文件流回来。

Just idea: 只是想法:

public HttpResponseMessage GetFile()
{
    FileStream file = XLGeneration.XLGeneration.getXLFileExigence();

    using(var sr = new StreamReader(file))
    {
        content = sr.ReadToEnd();

        return new HttpResponseMessage
        {
            Content = new StringContent(content, Encoding.UTF8, "application/json")
        };
    }
}

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

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