Word,excel文件不在浏览器中显示

时间:2014-06-30 10:43:45

标签: c# excel pdf

以下代码位于我的.cs文件中。

protected void btnView_Click(object sender,EventArgs e)     {

    string strurl = "ViewFile.ashx?Name=Img/FT.pdf";//Welcome.docx";
    string StrPop = "window.open('"+strurl+"', '_newtab')";
    ScriptManager.RegisterClientScriptBlock(sender as Control, this.GetType(), "OpenWindow", StrPop, true);
}

ViewFile.ashx代码。

public void ProcessRequest(HttpContext context) {

bool freeDownload = true;

    string supportingFile = context.Request.QueryString["Name"].ToString();
    string strpath = HttpContext.Current.Server.MapPath(supportingFile);
    string strname = Path.GetFileName(strpath);
    string strextension = Path.GetExtension(strpath);
    string strtype = "";

    if (strextension != null)
    {
        switch (strextension.ToLower())
        {
            case ".htm":
            case ".html":
                strtype = "text/HTML";
                break;

            case ".txt":
                strtype = "text/plain";
                break;
            case ".doc":
                strtype = "application/msword";
                break;
            case ".rtf":
                strtype = "application/msword";
                break;
            case ".docx":
                strtype ="application/vnd.openxmlformats-officedocument.wordprocessingml.document" ; //"application/msword";
                break;
            case ".xls":
                strtype = "application/vnd.ms-excel";
                break;
            case ".xlsx":
                strtype = "application/vnd.ms-excel";
                break;
            case ".pdf":
                strtype = "Application/pdf";
                break;
        }
    }
    if (freeDownload)
    {
       // context.Response.AppendHeader("content-disposition", "inline: filename=\"" + strname + "\"");
    }
    if (strtype != null)
    {
        FileInfo file = new FileInfo(strpath);
        context.Response.ContentType = strtype;
        context.Response.AddHeader("Content-Disposition", "inline; filename=\"" + file.Name + "\"");
        context.Response.AddHeader("Content-Length", file.Length.ToString());
        context.Response.TransmitFile(file.FullName);
        context.Response.WriteFile(strpath);
        context.Response.Flush();
        context.Response.End();

    }

}
请朋友帮帮我吗?当我点击查看按钮,如果它是PDF文件,它显示在浏览器中。但如果它是.docx,doc,.xlsx,..它将直接下载。如何在浏览器中显示该文件?

1 个答案:

答案 0 :(得分:0)

您可以在按钮上单击创建FolderBrowserDialog,将其过滤到相关扩展,然后将其显示给用户,如下所示:

FolderBrowserDialog browseDialog;

browseDialog.Filter=" Wordfile (*.dotm; *.dot; *.docx; *.dotx; *.doc; *.docm; *.rtf; *.txt)|*.dotm; *.dot; *.docx; *.dotx; *.doc; *.docm; *.rtf; *.txt";  

if (browseDialog.ShowDialog() == DialogResult.OK)
    {
       MessageBox.Show( System.IO.Path.GetFullPath(browseDialog.FileName));
    }