Java Web(13)struts2 file upload 臨時文件命名問題

1. strut2 上傳文件的功能已經封裝好了,只要action類中定義好與表單一致的name的屬性就能夠輕鬆獲取到上傳的文件,html

<!-- enctype="multipart/form-data" 是必須的,若是不添加這個屬性,便不能正常上傳-->
<form action="upload"  method="post" enctype="multipart/form-data" id="excelForm">
	 <div>
		<label for="excelfileupload">&nbsp;選擇 Excel 文件上傳&nbsp;</label>
		<input type="file" class="form-control" id="excelfileupload" name="excel" >
		
		<button type="submit"  id="fileUploadModalBtn">上傳</button>
	 </div>	
</form>

2. 在上面的表單中,在action類中應該是這樣定義java

public class Upload extends ActionSupport {
    //對應input name=excel
    private File excel ;
    // XFileName 用於接收上傳文件的文件名
    private String excelFileName;
    // 文件的類型
    private String excelContentType ;
    
    public String execute(){
        // do something 
        return Action.SUCCESS ; 
        
    }
    
    // setter and getter 
}

3. 在成功接收了上傳的文件後,文件會被struts默認保存在一個緩存目錄中,緩存的目錄能夠在struts.properties 中修改apache

struts.multipart.saveDir= 你自定義目錄

 

4. 而後,出現了一個問題,若是是在eclipse的IDE環境中編碼測試,咱們能夠在workspace下的api

%eclipse_workspace%\.metadata\.plugins\org.eclipse.wst.server.core\tmp0\work\Catalina\localhost\

有相應項目目錄下找到上傳的臨時文件,能夠發現,上傳的文件是*.tmp的,無論是什麼文件,一上傳就變了*.tmp。若是是上傳excel文件 ,而後使用poi來解析,就會出錯,由於經過poi的org.apache.poi.ss.usermodel.WorkbookFactory來建立workbook,是拋異常的。必須把文件恢復到相應的文件後綴名。緩存

5. 還一個,在struts 的 Documentation 中就有說起到,要在本身的action中保存好session

When a file is uploaded it will typically be stored in a temporary directory. 
Uploaded files should be processed or moved by your Action class to ensure the data is not lost.

6. 問題又來了,如何在action中獲取到項目的路徑呢,在action中的session已經被封裝成了一個Map<String, Object>的對象,只能往裏填充數據和獲取數據,這時,咱們需求struts的一個類來爲咱們獲取到ServletContext,而後就能夠getRealPath()了咯。eclipse

這個類是 org.apache.struts2.ServletActionContext 能夠經過它的靜態方法獲取到ServletContext的引用。maven

7.最後 ,就是在相應的目錄中使用java.io.File.renameTo()來轉存文件,這時須要注意的是,調用了file.renamTo(newFile)後,並非file就變成了新的File的對象的引用 ,而是參數中的newFile持有轉存後的文件的File 引用。並且在引用renameTo返回的是boolean,這時應該判斷一下,是否轉存成功,否則後面的代碼中對newFile的引用就會拋異常FileNotFoundException。post

相關文章
相關標籤/搜索