【问题标题】:PPT not downloading in MVC applicationPPT没有在MVC应用程序中下载
【发布时间】:2013-07-26 07:01:05
【问题描述】:

我正在尝试将项目文件夹中存在的 PPT 下载到下载文件夹中。

        System.IO.FileInfo file = new System.IO.FileInfo(HttpContext.Server.MapPath("~/Output/Document.pptx"));
        DownloadPPT("Document.pptx", file);  

这是下载PPT功能:

    public void DownloadPPT(string fileName, System.IO.FileInfo file)
    {
        if (!file.Exists)
        {

        }
        else
        {
            // clear the current output content from the buffer
            Response.Clear();

            // add the header that specifies the default filename for the 
            // Download/SaveAs dialog 
            Response.AddHeader("Content-Disposition", "attachment; filename=" + fileName);

            //// add the header that specifies the file size, so that the browser
            //// can show the download progress
            //Response.AddHeader("Content-Length", file.Length.ToString());

            // specify that the response is a stream that cannot be read by the
            // client and must be downloaded
            Response.ContentType = "application/vnd.ms-powerpoint";
            // send the file stream to the client
            Response.WriteFile(Server.MapPath("~/Output/Document.pptx"));
        }
    }  

没有错误但没有下载ppt。
有人能说出我的代码有什么问题吗?

【问题讨论】:

  • 如果你在一个 MVC 控制器动作中,你可以使用像 return File 这样的 MVC Utility 方法并且返回类型为 FileResult
  • 您是在控制器方法中调用您的第一个代码 sn-p 吗?如果是这样,您能否发布控制器方法的代码(或至少从该代码 sn-p 到末尾)?
  • 不,我不在 ActionResult 中。我需要处理此代码本身的下载。不过感谢您的建议。
  • 可能文件不存在? : ) 并且代码首先完成执行 if。你调试了吗?
  • 文件存在。 else 部分条件被调用。

标签: c# asp.net-mvc


【解决方案1】:

你可以试试这段代码:

Response.Clear();
Response.AddHeader("Content-Disposition", "attachment; filename=" + fileName);
Response.ContentType = "application/vnd.ms-powerpoint";
Response.Buffer = true;

using (FileStream fileStream = File.Open(Server.MapPath("~/Output/Document.pptx"), FileMode.Open)
{
    fileStream.CopyTo(Response.OutputStream);
}

Response.End();

我不能确切地告诉你你的代码有什么问题,但我在非常相似的环境中使用这个 sn-p,它一直对我有用。 如果没有,也许是因为您的情况有其他情况? 看来您可以访问 Response 属性,这就是为什么我想不出任何会阻止此 sn-p 正常工作的原因。但如果这没有帮助,肯定还有其他人比我更有经验。

【讨论】:

  • 仍然没有下载:(
  • 如果可能的话,我建议将您的代码放在 MVC 操作中。如果没有,您能否在您所处的环境中提供更多详细信息?如果这是某种后台进程,您将无法让浏览器下载文件,因为请求可能已经结束,服务器无法再向浏览器推送新数据
  • 您的第二个原因可能是正确的。但我不确定它是否属实以及如何解决。
  • 那将是一个更复杂的情况。如果您的代码在某个后台进程中并且Response 上下文不再可用,您有两个基本选择:将您的工作放在请求线程中并保持请求打开,直到您可以将文档发送到浏览器。但是,如果您的主要请求已经发送了一些其他信息,这将不起作用。第二种选择是让浏览器通过javascript 轮询文档的状态。当文件准备好下载时,您可以使用 url 回答该轮询,浏览器可以使用它来下载文件(MVC 操作)。
【解决方案2】:

一个建议是使用 iframe,它将推送非渲染格式文件下载..

更多信息here

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-09-23
    • 2015-02-07
    • 1970-01-01
    • 2018-06-16
    • 1970-01-01
    • 2021-12-07
    相关资源
    最近更新 更多