1. 程式人生 > >用struts2實現上傳檔案和轉化檔案為html

用struts2實現上傳檔案和轉化檔案為html

action

public class shangchuanAction extends ActionSupport{
	public File some;
	public String someFileName;
	public File getSome() {
		return some;
	}
	public void setSome(File some) {
		this.some = some;
	}
	public String getSomeFileName() {
		return someFileName;
	}
	public void setSomeFileName(String someFileName) {
		this.someFileName = someFileName;
	}
		public String excute() throws Exception {

		String path="/upload/"+ someFileName;
		String path1=ServletActionContext.getServletContext().getRealPath(path);
		File dic = new File(ServletActionContext.getServletContext().getRealPath("/upload"));
		if(!dic.exists()) {        //資料夾自動生成
			dic.mkdir();
		}
		System.out.println(path1); //輸出上傳到的地址
		File f = new File(dic,someFileName);
		try {
			//儲存檔案到專案的資料夾下
			FileUtils.copyFile(some,f);
		} catch (IOException e) {
			e.printStackTrace();
		}
		WordReader.extractDoc(path1,path1.replace(".docx", ".html"));//轉化word為html
		return "success";
	}

轉換為html的類 只搞上傳不用
下載jacob-1.19.zip解壓後匯入裡面的jacob.jar包,複製相應的.dll檔案到jdk和jre安裝的bin目錄下

package com.test;

import com.jacob.activeX.ActiveXComponent;
import com.jacob.com.Dispatch;
import com.jacob.com.Variant;
public class WordReader {
	 public static void extractDoc(String inputFIle, String outputFile) {
	        boolean flag = false;
	        // 開啟Word應用程式
	        ActiveXComponent app = new ActiveXComponent("Word.Application");
	        try {
	            // 設定word不可見
	            app.setProperty("Visible", new Variant(false));
	            // 開啟word檔案
	            Dispatch doc1 = app.getProperty("Documents").toDispatch();
	            Dispatch doc2 = Dispatch
	                .invoke(doc1, "Open", Dispatch.Method, new Object[] {inputFIle, new Variant(false), new Variant(true)},
	                        new int[1]).toDispatch();
	            // 作為html格式儲存到臨時檔案::引數 new Variant(8)其中8表示word轉html;7表示word轉txt;44表示Excel轉html。。。
	            Dispatch.invoke(doc2, "SaveAs", Dispatch.Method, new Object[] {outputFile, new Variant(8)}, new int[1]);
	            // 關閉word
	            Variant f = new Variant(false);
	            Dispatch.call(doc2, "Close", f);
	            flag = true;
	        } catch (Exception e) {
	            e.printStackTrace();
	        } finally {
	            app.invoke("Quit", new Variant[] {});
	        }
	        if (flag == true) {
	            System.out.println("Transformed Successfully");
	        } else {
	            System.out.println("Transform Failed");
	        }
	    }
}

上傳jsp程式碼

<form action="shangchuanAction" method="post" enctype="multipart/form-data">
    選擇一個檔案:
    <input type="file" name="some"/>
    <br/><br/>
    <input type="submit" value="上傳"/>
</form>