Struts上傳照片到服務器

               關於Struts上傳照片的功能,可能很多人都已經接觸過了。我記得我之前做過一個上傳Jar包的功能,那時候是用SpringMVC做的,先做一個類似於上傳的功能,將Jar包添加進行之後解讀Jar包,是因爲要拿到Jar包裏面的類名、屬性名和中文註釋,但是又沒辦法手動將所有Jar包拷貝到項目下,所以想着用上傳的方式來實現。現在是要做上傳照片。將用戶的照片保存到服務器的文件夾下,如果該文件夾存在,則直接上傳,如果不存在就創建該文件夾然後再上傳。

前臺代碼:
<pre name="code" class="html"><span style="font-size:14px;"><form name="webform" method="post" action="personBaseInfo_upload_employee_newEmploy.action" enctype="multipart/form-data" >
	<table id="sreachArea" width="100%" border="0" cellspacing="1" cellpadding="0" class="module_table_bg">
		<tr>
			<td class="content_title_right" rowspan="6" width="10%">照片:</td>														
			<td class="content_content"  width="40%" rowspan="6" align="center" >
			<input name="pic" type="file" style="display:none" >
			<input type="hidden" id ="SGuid" value="${personPhotoInfo.SGuid }" name="personPhotoInfo.SGuid"/>						
			<input type="hidden" id ="SPersonGuid" value="${personPhotoInfo.SPersonGuid }" name="personPhotoInfo.SPersonGuid"/>						
				<a href="javascript:void(sDialog());" >
				c:if test="${personPhotoInfo.SFilePath != null}">
					<img src="${appPath}/uploadImage//${personPhotoInfo.SFileIname}" width="105px;" height="130px;"></img>
				</c:if>
				<c:if test="${personPhotoInfo.SFilePath == null}">
					<img src="${appPath}/common/images/login/UserImg.jpg" width="105px;" height="130px;"></img>
				</c:if> 							
				</a>
				<input type="submit" value="上傳"/>	
			</td>	
		</tr>		
	</table>
</form></span>

JS函數:
<span style="font-size:14px;">//上傳照片響應
function sDialog() {
	var dataForm = document.forms['webform'];
	dataForm.pic.click();
}</span>
後臺圖片上傳代碼:
<span style="font-size:14px;">/** 
* 功能:文件上傳 
* @author gaoying
* @return 跳轉頁面的字符串 
* @throws IOException 
* @throws ParseException 
*/  
public String upload(){ 
	personPhotoInfo = new PersonPhotoInfo();
	try { 
	    //服務器路徑
	    String serverPath = ServletActionContext.getServletContext().getRealPath("/");
	    System.out.println("服務器路徑爲:" + serverPath);
	    System.out.println("打印一下:" + serverPath + "uploadImage");
	    //判斷服務器上是否有uploadImage這個文件夾,如果沒有則創建
	    if(!(new File(serverPath + "uploadImage").isDirectory())){
	        //mkdir創建一層目錄;mkdirs爲創建多層目錄
	        new File(serverPath+"uploadImage").mkdir();
	    }
	        		        	
	    //服務器的路徑  
	    String realpath = ServletActionContext.getServletContext().getRealPath("/uploadImage");  
	    System.out.println("上傳到服務器的地址realpath: "+realpath);   
		 
	    //給文件重新命名
	    File exFileName = new File(picFileName);  //picFileName爲原文件名            
	    //System.out.println("重命名後的文件名稱:" + renameFile(exFileName));
	    newFileName = renameFile(exFileName);  //給上傳文件重命名
	    //具體地址+文件名    
	    fileSavePath = realpath+"\\"+renameFile(newFileName);  //文件保存的路徑名+文件名
	    System.out.println("文件保存的路徑名+文件名:" + fileSavePath);
	    //列如------  E:\workspace\tomcat\webapps\sems\\005.jpg  
		
	    if (pic != null) {              
	        File savefile = new File(new File(realpath), newFileName.toString());              
	        if (!savefile.getParentFile().exists())   
	            savefile.getParentFile().mkdirs();    
	        FileUtils.copyFile(pic, savefile);    
	        ActionContext.getContext().put("message", "文件上傳成功");   
	    } 	 	                   
	            
	    //將照片信息保存到數據庫
	    personPhotoInfo.setSFileIname(newFileName.toString());//文件存儲名稱
	    personPhotoInfo.setSFilePath(fileSavePath);  //文件存儲路徑	            
	    personPhotoInfo.setSGuid(UUIDHexGenerator.getUUID());  	
	    personPhotoInfo.setSFileInitialName(picFileName);  //上傳文件原名         	            
	    personPhotoInfo.setSFileExtension(picFileName.substring(picFileName.lastIndexOf('.')));
	    personPhotoInfo.setSPersonGuid(personBaseInfo.getSGuid());  //人員id
	    personPhotoInfo.setSUploadDate(new Date());
	        	
		personPhotoInfoManager.savePersonPhotoInformation(personPhotoInfo);
	} catch (Exception e) {  
	    e.printStackTrace();  
	}                  
	return SUCCESS; 
} </span>
文件重命名代碼:
<span style="font-size:14px;">/**
 * <p>Description: 上傳文件重命名</p>
 * @param file 文件名
 * @return 文件
 * @author       : gaoying
 * @update       :
 * @date         : 2015-7-26
 */
public File renameFile(File file){
	String body = "";
	String ext = "";
	Date date = new Date();
	int pot = file.getName().lastIndexOf(".");
	if(pot != -1){
	    body = date.getTime() +"";
	    ext = file.getName().substring(pot);
	}else{
	    body = (new Date()).getTime()+"";
	    ext = "";
	}
	String newName = body + ext;
	file = new File(file.getParent(), newName);
	return file;
}</span>
       這樣,整個Struts上傳圖片到服務器的功能就完成了。其實整個流程重要的代碼就那麼幾句,還有就是上傳照片的時候要注意一定要把文件重命名之後再上傳。還有,前臺是瀏覽輸入上傳文件和submit按鈕,只不過我前臺處理讓上傳文本框隱藏了,所以點擊用戶照片的位置就能直接上傳。本來想着也想把submit按鈕給去掉呢,但是又沒辦法觸發事件了。各位要是有好的想法,歡迎在下方留言,我們一起討論、交流。


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章