是否可以从Asp.net中的[Httppost]的HttpResponseMessage类型返回文件mvc [复制]

问题描述 投票:0回答:1

这个问题在这里已有答案:

我正在开发一个项目,将文件从html转换为pdf,以获得pdf客户端首先使用文件对话框选择html然后发送到控制器而不是此控制器接收文件并成功转换为pdf但问题是他无法下载文件直到方法是POST,

调节器

   [HttpPost]
  public HttpResponseMessage Dashboard(HttpPostedFileBase file,string typeofmodel)
    {


    var htmlToPdf = new HtmlToPdfConverter();

        var stream = new MemoryStream();
        var pdfContentType = "application/pdf";
        // processing the stream.
        BinaryReader b = new BinaryReader(File.InputStream);
        byte[] binData = b.ReadBytes(File.ContentLength);

        string html = System.Text.Encoding.UTF8.GetString(binData);
        stream.Write(htmlToPdf.GeneratePdf(html, null), 0, htmlToPdf.GeneratePdf(html, null).Length);

        var result = new HttpResponseMessage(HttpStatusCode.OK)
        {
            Content = new ByteArrayContent(stream.ToArray())
        };
        result.Content.Headers.ContentDisposition =
            new System.Net.Http.Headers.ContentDispositionHeaderValue("attachment")
            {
                FileName = "Htmltopdf.pdf"
            };
        result.Content.Headers.ContentType =
            new MediaTypeHeaderValue(pdfContentType);

        return result;
    }

这里HtmlToPdfConverter是一类NReco库,可以找到Here

产量

StatusCode:200,ReasonPhrase:'OK',版本:1.1,内容:System.Net.Http.ByteArrayContent,Headers:{Content-Disposition:attachment; filename = Htmltopdf.pdf内容类型:application / pdf}

请帮忙怎样才能返回下载?仅使用HTTPPOST。

c# asp.net model-view-controller
1个回答
0
投票

HttpResponseMessage是stringyfied,因为它不是ActionResult。 Controller的动作必须返回一个ActionResult:

public ActionResult Dashboard(HttpPostedFileBase file,string typeofmodel)
{


   var htmlToPdf = new HtmlToPdfConverter();

    var stream = new MemoryStream();
    var pdfContentType = "application/pdf";
    // processing the stream.
    BinaryReader b = new BinaryReader(File.InputStream);
    byte[] binData = b.ReadBytes(File.ContentLength);

    string html = System.Text.Encoding.UTF8.GetString(binData);
    stream.Write(htmlToPdf.GeneratePdf(html, null), 0, htmlToPdf.GeneratePdf(html, null).Length);

    return File(stream, pdfContentType, "Htmltopdf.pdf"); 

}
© www.soinside.com 2019 - 2024. All rights reserved.