MVC FileStreamResult 未下载具有自定义文件名的文件

问题描述

pdf 下载正常,但名称随机的 - 9619012021194536.pdf
我正在尝试设置自定义名称,但它不起作用。 下载的文件仍然有一个随机名称,而不是代码中设置的自定义名称

public ActionResult Appointment(int id)
        {
            Stream stream = null;
            string fileName = "";

            try
            {
                stream = GenerateAppointmentReport(id);
                fileName = id + "_" + DateTime.Now.ToString("ddMMyyyyHHmmss") + ".pdf";                    
            }
            catch (Exception ex)
            {
                
            }

            return new FileStreamResult(stream,MimeMapping.GetMimeMapping(fileName))
            { FileDownloadName = fileName };
        }

解决方法

您可以使用此代码:

public ActionResult Appointment(int id)
{
  Stream stream = null;
  string fileName = "";

  try
  {
     stream = GenerateAppointmentReport(id);
     fileName = id + "_" + DateTime.Now.ToString("ddMMyyyyHHmmss") + ".pdf";                    
  }
  catch (Exception ex)
  {
                    
  }
  return new FileStreamResult(stream,"binary") { FileDownloadName = fileName };
}

我使用了此代码,并且使用我提到的特定名称下载了该文件。

,

您可以将数据绑定到 GridView 类型的临时对象中,然后将对象写入输出流,如下所示:

    public ActionResult Appointment(int id)
    {
    
    GridView gridview = new GridView();
    gridview.DataSource = fileData; //fileData is an object with all the properties
    gridview.DataBind();
    
    Response.ClearContent();
    Response.Buffer = true;
    
tmpfileName = id + "_" + DateTime.Now.ToString("ddMMyyyyHHmmss") + ".pdf";

    Response.AddHeader("content-disposition","attachment; filename = " + tmpfileName);
    Response.ContentType = "application/pdf";
    Response.Charset = "";
    
                using (StringWriter sw = new StringWriter())
                {
                    using (HtmlTextWriter htw = new HtmlTextWriter(sw))
                    {
                        gridview.RenderControl(htw);
                        Response.Output.Write(sw.ToString());
                        Response.Flush();
                        Response.End();
                    }
                }
    
    return RedirectToAction("Appointment"); // To another/same action
    }