浏览器上的文件内容查看器使用asp.net

时间:2011-12-02 17:15:24

标签: c# asp.net

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

谢谢..

2 个答案:

答案 0 :(得分:2)

您将无法看到任何文件的内容,因为这会要求相关浏览器有一个插件来显示特定文件。以MS Project文件,Corel Draw文件和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是应用程序中包含这些文件的虚拟目录。

答案 1 :(得分:0)

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

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

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

以下是本答案末尾的类中StreamFileToUser方法中实现的下载过程的说明:

如果调用者请求下载,那么我们检查一组mime类型以确定该文件是否包含支持的mimetype,这意味着它有可能被内联显示给用户。

如果找到mime类型,我们使用inline指令要求浏览器向用户显示该文件。如果浏览器不支持为此mime类型进行内联,则系统将提示用户下载。

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

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

以下是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子目录中。