页面代码:
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title>附件上传</title>
<style type="text/css">
*
{
color: #383838;
font-size: 12px;
margin:0;
padding:0;
}
#container table
{
margin:50px auto 0 auto;
}
</style>
</head>
<body>
<form id="form1" runat="server">
<div id="container">
<table cellpadding="0" cellspacing="0">
<tr>
<td>
请选在要上传的文件(最大4M):
</td>
<td>
<asp:FileUpload ID="FileUpload1" Width="250px" runat="server" />
</td>
</tr>
<tr>
<td>
上传 Word文档将生成在线查看文档!
</td>
<td>
<asp:Button ID="btnSubmit" runat="server" Text="确定上传" OnClick="btnSubmit_Click" />
<asp:HyperLink ID="HyperLink1" runat="server" Visible="false">查看生成文档</asp:HyperLink>
</td>
</tr>
</table>
</div>
</form>
</body>
</html>
后台代码:
protected void btnSubmit_Click(object sender, EventArgs e)
{
HttpPostedFile upLoadFile = FileUpload1.PostedFile;
if (upLoadFile.ContentLength >= 4194304)
{
//如果上传文件大于4M则提示用户上传附件失败
ScriptManager.RegisterClientScriptBlock(btnSubmit, btnSubmit.GetType(), null, "<script>alert('上传失败,文件不能大于4M!')</script>", false);
}
else
{
//此处的处理方法是将doc文件直接转为html文件,存放在服务器的某个路径下,然后直接读取即可
//用到的类库是Microsoft.Office.Interop.Word,此类库net自带,不必自行下载 modify by Vincnet.Q 10.11.27
string fileName = upLoadFile.FileName.Substring(upLoadFile.FileName.LastIndexOf("\\"));
string fileExtension =upLoadFile.FileName.Substring( upLoadFile.FileName.LastIndexOf(".")+1).ToLower();
string path = Server.MapPath("UpLoadFiles") + "\\" +fileName ;
upLoadFile.SaveAs(path);
if (fileExtension == "doc" || fileExtension == "docx")
{
#region 定义打开word文档发方法的参数
object filePath = Server.MapPath("UpLoadFiles\\"+fileName);
object readOnly = true;
object addToRecentFiles = false;
object confirmConversion = false;
object revert = true;
object visible = false;
object formate = WdSaveFormat.wdFormatFilteredHTML;
object missing = System.Reflection.Missing.Value;
object savePath = Server.MapPath("GenerationFiles\\"+fileName.Replace(fileExtension,"html"));
object saveChanges = false;
#endregion
//word引用程序
Application word = new Application();
//打开一个文档
Document doc = word.Documents.Open(ref filePath,
ref confirmConversion, ref readOnly, ref addToRecentFiles, ref missing, ref missing, ref revert, ref missing, ref missing, ref missing, ref missing,
ref visible, ref missing, ref missing, ref missing, ref missing);
//另存为网页格式
doc.SaveAs(ref savePath, ref formate, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing);
word.Quit(ref saveChanges, ref missing, ref missing);
HyperLink1.Visible = true;
HyperLink1.NavigateUrl = "GenerationFiles" + fileName.Replace(fileExtension, "html");
//显示出路径
HyperLink1.Text = HyperLink1.NavigateUrl;
}
ScriptManager.RegisterClientScriptBlock(btnSubmit, btnSubmit.GetType(), null, "<script>alert('上传附件成功')</script>", false);
}
}