【问题标题】:Viewing file using asp.net使用 asp.net 查看文件
【发布时间】:2010-11-16 15:58:37
【问题描述】:

在我们的应用程序中,我们允许用户上传文档,可以是 PDF、Doc、XLS、TXT。上传的文件将保存在网络服务器上。我们需要为用户上传的每个文档显示链接,当用户单击该链接时,它应该打开相关文档。预计需要软件才能打开相关文档。

要上传文档,我们使用 FileUpload 控件的 saveAs 方法,它工作得非常好。 那么,如何查看呢?

我相信,我需要将文件复制/下载到本地用户机器并需要使用 Process.Start 打开它。

为此,我需要找到用户本地临时目录。如果我放 path.GetTempPath(),它会给我 Web 服务器目录并在那里复制文件。

File.Copy(
   sPath + dataReader["url"].ToString(),
   Path.GetTempPath() + dataReader["url"].ToString(), 
   true);

请指教。

【问题讨论】:

    标签: asp.net


    【解决方案1】:

    您无法从网络服务器写入用户驱动器。

    可以做的只是提供一个将文件下载到客户端的链接。 将Content-Disposition 标头设置为“附件”以显示“另存为”对话框,或设置为“内联”以使用客户端注册的程序在浏览器中显示。

    您可以使用包含如下代码的服务器端处理程序创建LinkButton

    byte[] data = ...; // get the data from database or whatever
    
    Response.Clear(); // no contents of the aspx file needed
    
    Response.CacheControl = "private";
    Response.ContentType = "application/pdf"; // or whatever the mimetype of your file is
    Response.AppendHeader("Content-Disposition", "attachment;filename=statistic.pdf");
    Response.AppendHeader("Content-Length", data.Length.ToString(CultureInfo.InvariantCulture));
    
    Response.BinaryWrite(data);
    
    Response.End(); // no further processing of the page needed
    

    【讨论】:

      【解决方案2】:

      你不能在页面上放一个指向文件所在目录的链接吗? 例如 <a href=downloadedfiles/filename.pdf> click here </a>

      【讨论】:

        【解决方案3】:

        提供链接后,您的工作就完成了。大多。客户端的浏览器将在单击链接时处理加载文件,如果它可以根据文件扩展名处理文件类型。

        我更喜欢使用 http 处理程序来引用网页上的文件链接。这在您需要为上传的文件访问实施安全性的那一天很重要;否则,任何用户都可以访问任何文件。

        【讨论】:

          【解决方案4】:

          您不必将文件下载到用户计算机。

          // For pdf documents
          Response.Clear();
          string filePath = "File path on the web server";
          Response.ContentType = "application/pdf";     // for pdf
          Response.WriteFile(filePath);
          
          // For word documents
          Response.Clear();
          string filePath = "File path on the web server";
          Response.ContentType = "application/msword";
          Response.WriteFile(filePath);
          
          // similarly other file types
          

          【讨论】:

            猜你喜欢
            • 1970-01-01
            • 1970-01-01
            • 2018-04-29
            • 2015-10-15
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 2023-03-09
            相关资源
            最近更新 更多