如何在MVC中的应用程序文件夹中保存任何文件/数据?

时间:2017-01-14 14:57:13

标签: asp.net-mvc

我正在使用库将HTML转换为PDF。转换为PDF后,如何将此转换的PDF文件保存在控制器的应用程序文件夹中? 这是代码:

public ActionResult ABC(ResearchProposal model)
{
    ViewDataDictionary viewData = new ViewDataDictionary(model);

    // transmit the posted data to view
    viewData["MyModel"] = model;

    StringWriter stringWriter = new StringWriter();

    // Render the Index view in a HTML string
    ViewEngineResult viewResult = ViewEngines.Engines.FindView(ControllerContext, "ABC", null);
    ViewContext viewContext = new ViewContext(
            ControllerContext,
            viewResult.View,
            viewData,
            new TempDataDictionary(),
            stringWriter
            );
    viewResult.View.Render(viewContext, stringWriter);

    // Get the view HTML string
    string htmlToConvert = stringWriter.ToString();

    // Get the base URL
    String currentPageUrl = this.ControllerContext.HttpContext.Request.Url.AbsoluteUri;
    String baseUrl = currentPageUrl.Substring(0, currentPageUrl.Length - "Reports/ABC".Length);

    // Create a HTML to PDF converter object with default settings
    HtmlToPdfConverter htmlToPdfConverter = new HtmlToPdfConverter();

    // Set license key received after purchase to use the converter in licensed mode
    // Leave it not set to use the converter in demo mode
    htmlToPdfConverter.LicenseKey = "fvDh8eDx4fHg4P/h8eLg/+Dj/+jo6Og=";

    // Set an adddional delay in seconds to wait for JavaScript or AJAX calls after page load completed
    // Set this property to 0 if you don't need to wait for such asynchcronous operations to finish
    htmlToPdfConverter.ConversionDelay = 2;

    // Convert the HTML string to a PDF document in a memory buffer
    byte[] outPdfBuffer = htmlToPdfConverter.ConvertHtml(htmlToConvert, baseUrl);


    // Send the PDF file to browser
    FileResult fileResult = new FileContentResult(outPdfBuffer, "application/pdf");

    fileResult.FileDownloadName = "Convert_Current_Page.pdf";

    return fileresult;
}

1 个答案:

答案 0 :(得分:0)

您可以使用File.WriteAllBytes来保存您获得的FileContentResult字节。

您需要映射服务器的相对路径才能使其正常工作,因为相对路径仅适用于ASP.NET的上下文。

string filename = "Convert_Current_Page.pdf";
string path = Server.MapPath("~G/Initial try/Content/data/");
path = Path.Combine(path, filename);

File.WriteAllBytes(path, fileResult.FilecContents);