【问题标题】:File Content viewer on browser using asp.net使用 asp.net 的浏览器上的文件内容查看器
【发布时间】:2011-12-03 03:31:37
【问题描述】:

如何在asp.net浏览器上查看上传文件的内容?是否可以使用通用代码查看所有类型文件的内容?或者那里有免费的项目?

谢谢..

【问题讨论】:

标签: c# asp.net


【解决方案1】:

您将无法看到任何文件的内容,因为这需要相关浏览器具有插件才能显示特定文件。以 MS 项目文件、Corel 绘图文件和 Auto CAD 为例,你有什么。自 AFAIK 以来,浏览器不会显示这些文件,没有为这些文件提供插件,浏览器可以使用这些插件在其中嵌入查看器。

浏览器通常会愉快地显示 PDF(前提是安装了 Acrobat Reader)、图像、TXT 文件和其他一些文件。

因此,您可以通过以下方式完美读取所有文件:

DirectoryInfo info = new DirectoryInfo("PhysicalPathToFiles");
GridView1.DataSource=info.GetFiles();
GridView1.DataBind();

并将您的 GrdiView1 标记设置为仅绑定 FileName 属性和您需要的所有其他内容。您希望在此列上构建一个超链接,以便在单击文件名时,根据文件类型要求用户下载/查看文件。

假设您将所有文件绑定到 Gridview,如上所述。拥有像这样的 GridViewColumn 应该允许用户单击任何文件并在浏览器中查看它。

<asp:HyperLinkColumn
                 HeaderText="File Name"
                 DataNavigateUrlField="Name"
                 DataNavigateUrlFormatString="UploadedFiles/{0}"
                 DataTextField="Name"
                 />

UploadedFiles 是您的应用程序中保存这些文件的虚拟目录。

【讨论】:

  • 对不起,我想在浏览器上查看文件的内容。
  • @Harikrishna:并非所有文件都可以在浏览器中“查看”。假设用户将 CorelDraw 文件上传到应用程序。浏览器将无法在其中显示它。一般来说,浏览器会愉快地显示 PDF、图像和 TXT 文件。你没有说你允许用户上传什么类型的文件,因此我的回答。
  • 是的,但是我想显示pdf,文本文件,word,excel等文件的内容,通常用于上传。那我能做些什么呢?
  • @Harikrishna:正如我所解释的,通过创建指向文件虚拟路径的链接,它将在浏览器中显示。让我更新我的答案并更好地解释我的意思。
  • 好的,谢谢,我等着。正如你之前所说,我想显示 PDF 的内容(前提是安装了 Acrobat Reader)、图像、TXT 文件和其他浏览器支持的文件。
【解决方案2】:

为了允许用户查看内联文件,您需要将文件流式传输给用户并在标题中设置一些值。

我们通常使用映射到“虚拟”页面(即 Download.aspx)的 HTTP 处理程序来执行此操作,以便可以在弹出窗口中从客户端调用它而不会影响调用页面。

此机制可用于下载或查看内联文件。

下面是本答案末尾类中StreamFileToUser方法实现的下载过程的描述:

如果调用者请求下载,则我们检查一组 mime 类型以确定文件是否包含受支持的 mimetype,这意味着它有机会内嵌显示给用户。

如果找到 mime 类型,我们使用 inline 指令要求浏览器将文件显示给用户。如果浏览器不支持这种 mime 类型的内联,则会提示用户下载。

如果我们没有找到 mime 类型,则会发出直接下载命令。

您可以通过打开 IIS 管理器、选择 Web 服务器图标并双击 Mime Types 图标来获取 IIS(假设 7+)中的完整 mime 类型列表。

以下是 HTTP 处理程序类的示例:

public class DownloadRequestHandler : System.Web.IHttpHandler, System.Web.SessionState.IRequiresSessionState
{
    public bool IsReusable
    {
        get
        {
            return false;
        }
    }

    /// <summary>
    /// This method is used to process the incoming request
    /// </summary>
    /// <param name="oContext"></param>
    /// <remarks></remarks>
    public void ProcessRequest(HttpContext oContext)
    {
        try
        {
            string sFileName = null;
            string sSourceFilePath = null;

            // Should add existence checking here
            sFileName = oContext.Request.QueryString["FileName"];

            // Assume that the files are stored in the relative directory Files. Should add existence checking here
            sSourceFilePath = System.IO.Path.Combine(oContext.Server.MapPath("Files"), sFileName);

            StreamFileToUser(GenerateStandardMimeList(), sSourceFilePath, sFileName, oContext.Response, false, false);
        }
        catch (System.Threading.ThreadAbortException theException)
        {
            // Do nothing
        }
        catch (Exception theException)
        {
            SendErrorToUser(oContext.Response, theException.Message);
        }
    }
    /// <summary>
    /// This method streams a file to a user
    /// </summary>
    /// <param name="cMimeTypes">The set of known mimetypes. This is only needed when the file is not being downloaded.</param>
    /// <param name="sFileName"></param>
    /// <param name="sFileNameForUser"></param>
    /// <param name="theResponse"></param>
    /// <param name="fDownload"></param>
    /// <returns></returns>
    /// <remarks></remarks>
    public bool StreamFileToUser(System.Collections.Generic.Dictionary<string, string> cMimeTypes, string sFileName, string sFileNameForUser, HttpResponse theResponse, bool fDownload = true, bool fOkToDeleteFile = false)
    {
        // Exceptions are handled by the caller

        bool fDontEndResponse = false;

        sFileNameForUser = CleanFileName(sFileNameForUser);

        // Ensure there is nothing else in the response
        try
        {
            try
            {
                // Remove what other controls may have been put on the page
                theResponse.ClearContent();
                // Clear any headers
                theResponse.ClearHeaders();
            }
            catch (System.Web.HttpException theException)
            {
                // Ignore this exception, which could occur if there were no HTTP headers in the response
            }

            bool fFoundIt = false;

            if (!fDownload)
            {
                string sExtension = null;

                sExtension = System.IO.Path.GetExtension(sFileNameForUser);
                if (!(string.IsNullOrEmpty(sExtension)))
                {
                    sExtension = sExtension.Replace(".", "");
                    if (cMimeTypes.ContainsKey(sExtension))
                    {
                        theResponse.ContentType = cMimeTypes[sExtension];
                        theResponse.AddHeader("Content-Disposition", "inline; filename=" + sFileNameForUser);
                        fFoundIt = true;
                    }
                }
            }

            if (!fFoundIt)
            {
                theResponse.ContentType = "application/octet-stream";
                theResponse.AddHeader("Content-Disposition", "attachment; filename=" + sFileNameForUser);
            }

            theResponse.TransmitFile(sFileName);

            // Ensure the file is properly flushed to the user
            theResponse.Flush();
        }
        finally
        {
            // If the caller wants, delete the file before the response is terminated
            if (fOkToDeleteFile)
            {
                System.IO.File.Delete(sFileName);
            }
        }

        // Ensure the response is closed
        theResponse.Close();

        if (!fDontEndResponse)
        {
            try
            {
                theResponse.End();
            }
            catch
            {
            }
        }

        return true;
    }

    /// <summary>
    /// This method generates a standard list of extension to content-disposition tags
    /// The key for each item is the file extension without the leading period. The value 
    /// is the content-disposition.
    /// </summary>
    /// <returns></returns>
    /// <remarks></remarks>
    public System.Collections.Generic.Dictionary<string, string> GenerateStandardMimeList()
    {
        // Exceptions are handled by the caller.

        System.Collections.Generic.Dictionary<string, string> cItems = new Dictionary<string, string>();

        cItems.Add("jpeg", "image/jpeg");
        cItems.Add("jpg", "image/jpeg");
        cItems.Add("pdf", "application/pdf");
        cItems.Add("csv", "application/vnd.ms-excel");
        cItems.Add("doc", "application/msword");
        cItems.Add("docx", "application/vnd.ms-word.document.12");
        cItems.Add("xls", "application/vnd.ms-excel");
        cItems.Add("xlsx", "application/vnd.ms-excel.12");

        return cItems;
    }

    /// <summary>
    /// This method removes all invalid characters from the specified file name.
    /// Note that ONLY the file name should be passed, not the directory name.
    /// </summary>
    /// <param name="sFileName"></param>
    /// <returns></returns>
    /// <remarks></remarks>
    public string CleanFileName(string sFileName)
    {
        // Exceptions are handled by the caller

        // If there are any invalid characters in the file name
        if (sFileName.IndexOfAny(System.IO.Path.GetInvalidFileNameChars()) >= 0)
        {
            // Strip them out (split to remove the characters, then rejoin the pieces into one string)
            return string.Join("", sFileName.Split(System.IO.Path.GetInvalidFileNameChars()));
        }
        else
        {
            return sFileName;
        }
    }

    public void SendErrorToUser(HttpResponse theResponse, string sError)
    {
        // Note that errors are handled by the caller

        sError = "<script>alert(\"" + sError.Replace("\"", "").Replace(Environment.NewLine, "\\n") + "\");</script>";
        // Ensure there is nothing else in the response
        theResponse.Clear();
        theResponse.Write(sError);
        theResponse.Flush();
    }
}

在您的 web.config 中,将以下行添加到 httphandlers 部分,并根据需要替换命名空间:

    <add path="download.aspx" verb="*" type="MyWebApp.DownloadRequestHandler, MyWebApp" validate="false" />

那么你的下载请求是:

download.aspx?FileName=thefile.pdf

上面的代码假定文件存储在网站的 Files 子目录中。

【讨论】:

  • 不需要向标题添加任何内容,如果您希望用户始终下载文件(通过添加内容处置)但要显示它,点击链接就足够了.
  • @Icarus:这实际上取决于链接的呈现方式;如果它是直接指向网站中文件的链接,那么您是正确的。但是,如果它是指向 HTTP 处理程序的链接(我在最后添加了一个简介),那么您肯定必须指定内容处置。
  • @competent_tech 我们也可以使用此代码查看 word 文件和 pdf 文件吗?
  • @Icarus 我看不到使用您答案中的代码的文件内容。我想我遗漏了一些东西,如何在应用程序中添加虚拟目录?
  • @Harikrishna:当然,假设用户安装了应用程序并且它们被配置为内联查看。 Acrobat 有一个选项允许最终用户关闭内嵌显示。我将更新 mime 类型以包含一些常见的 office doc 类型。
猜你喜欢
  • 2011-04-19
  • 2015-04-13
  • 2023-02-08
  • 1970-01-01
  • 2022-08-10
  • 2017-10-07
  • 2023-03-18
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多