asp.net 上传word 转化成HTML 并且将文件名更改为时间

    最近接到这样的一个任务,要给某个内网公告栏增加预览功能。具体要求如下:

1.首先允许用户上传word文件

2.为了避免上传word时候出现同名现象(比如文件名都为“新建XXX1”),要把上传的文件的名称改为当时的时间(精确到毫秒)。

3.添加预览功能,把word文件在网页上显示。与此同时要保留下载word这个功能。

 

一、上传wrod文件功能实现。

这里我使用了FileUpload这个控件。

这个控件有3个基本的属性:

FileName:获取上传文件的文件名

HasFile:是否选择(存在)上传文件

ContentLength:获得上传文件的大小,单位是字节(byte)
2个基本方法:

Server.MapPath():获取项目在服务器上的物理路径

举例:Server.MapPath("./File/") 表示的路径是项目中的File文件夹

SaveAs():保存文件到指定的文件夹 

举例:FileUpload1.SaveAs(path) path为路径

注意:默认情况下限制上传文件的大小为4MB,通过web.config.comments(这个设置是全局的配置)可以修改其默认设置

或者通过修改web.config文件来改变应用程序上传限制。

 

二、将文件名改成当前时间

    因为要防止重名状况的发生,因此在word上传的第一时间就要将文件名改成当时的时间。

string path = Server.MapPath("./File/") + FileUpload1.FileName;
string newWordPath = Server.MapPath("./File/")
                  + DateTime.Now.Year + "-" + DateTime.Now.Month + "-" + DateTime.Now.Day
                  + "-" + DateTime.Now.Hour + "-" + DateTime.Now.Minute + "-" + DateTime.Now.Second
                  + "-" + DateTime.Now.Millisecond + ".doc";
File.Move(path, newWordPath);//path为word文件在服务器上的路径newWordPath为以时间为文件名的word文件

 

三、转换成html

    要实现预览功能,首先要将word转换成HTML格式,然后在浏览器中打开。以下是word转成html类的代码。

注意:本人使用的是vs2012,其中包含了office组件。

    public static string WordToHtml(string filePath, string htmlFilePath)
    {
        Word.Application word = new Word.Application();
        Type wordType = word.GetType();
        Word.Documents docs = word.Documents;
        Type docsType = docs.GetType();
        Word.Document doc = (Word.Document)docsType.InvokeMember("Open", System.Reflection.BindingFlags.InvokeMethod, null, docs, new Object[] { (object)filePath, true, true });
        Type docType = doc.GetType();
        string strSaveFileName = htmlFilePath;
        object saveFileName = (object)strSaveFileName;
        docType.InvokeMember("SaveAs", System.Reflection.BindingFlags.InvokeMethod, null, doc, new object[] { saveFileName, Word.WdSaveFormat.wdFormatFilteredHTML });
        docType.InvokeMember("Close", System.Reflection.BindingFlags.InvokeMethod, null, doc, null);
        wordType.InvokeMember("Quit", System.Reflection.BindingFlags.InvokeMethod, null, word, null);
        Thread.Sleep(3000);//为了使退出完全,这里阻塞3秒
        return strSaveFileName;
    }

直接调用即可。

htmlpath = Office2Html.WordToHtml(newWordPath);

下载文件的路径为newWordPath。

预览文件的路径为html。

posted @ 2013-10-15 15:42  ThxMint  阅读(509)  评论(0编辑  收藏  举报