John
John

Reputation: 1499

Prevent code from prompting user to save file

I use this method below in my report controller. It succesfully returns file content which I assign to a varBinary(MAX) field in my database. My problem is, when this code executes it causes the browser to prompt the user to SAVE or OPEN the file. I want to stop this from happening.

How can I force it to only return the binary data to the calling controller method and not push results to the client browser?

private FileContentResult RenderReportFile(LocalReport localReport, List<ReportDataSource> listDS, string sFilename, string sReportType, bool bLandscape)
{
    string sHeight = "11";
    string sWidth = "8.5";

    if (bLandscape)
    { sWidth = sHeight; sHeight = "8.5"; }

    foreach (ReportDataSource ds in listDS)
    {
        localReport.DataSources.Add(ds);
    }

    HttpContextBase imageDirectoryPath = HttpContext;

    string reportType = sReportType;
    string mimeType;
    string encoding;
    string fileNameExtension;

    //The DeviceInfo settings should be changed based on the reportType
    string deviceInfo =
        "<DeviceInfo>" +
        "  <OutputFormat>" + sReportType + "</OutputFormat>" +
        "  <PageWidth>" + sWidth + "in</PageWidth>" +
        "  <PageHeight>" + sHeight + "in</PageHeight>" +
        "  <MarginTop>0.5in</MarginTop>" +
        "  <MarginLeft>0.5in</MarginLeft>" +
        "  <MarginRight>0.5in</MarginRight>" +
        "  <MarginBottom>0.5in</MarginBottom>" +
        "</DeviceInfo>";

    Warning[] warnings;
    string[] streams;
    byte[] renderedBytes;

    //Render
    renderedBytes = localReport.Render(
        reportType,
        deviceInfo,
        out mimeType,
        out encoding,
        out fileNameExtension,
        out streams,
        out warnings);


    //Write to the outputstream
    //Set content-disposition to "attachment" so that user is prompted to take an action
    //on the file (open or save)

    Response.Clear();
    Response.ContentType = mimeType;
    Response.AddHeader("content-disposition", "attachment; filename=" + sFilename + "." + fileNameExtension);
    Response.BinaryWrite(renderedBytes);
    Response.End();
    return File(renderedBytes, "application/pdf", sFilename + "." + fileNameExtension);
}

Upvotes: 0

Views: 131

Answers (1)

Peter
Peter

Reputation: 27944

This code is responsible for sending the document to the client:

Response.Clear();
Response.ContentType = mimeType;
Response.AddHeader("content-disposition", "attachment; filename=" + sFilename + "." + fileNameExtension);
Response.BinaryWrite(renderedBytes);
Response.End();

Remove it and the user will not be prompted for save or open.

Upvotes: 1

Related Questions