struts2+hibernate上傳name值不同的多個文件

iamhere,always.

---幸運皮

以前的時候,好像做過任意上傳多個文件的.哦,不對,應該是這樣說,最最初,是上傳固定的一個文件,用的struts2和hibernate,後來,做了固定上傳多個的,再後來,做了不固定個數上傳的,現在總結起來有這麼幾種情況:

<input type="file" name="upload"/>

看上面的文件代碼,我們分這麼幾種上傳的情況:

一,上傳一個文件,當然,這樣的話,name值只有一個

二,上傳多個.上傳多個其實包含了固定個數上傳和不定個數的上傳,一般來說,不定個數上傳,那麼,name的值一般都是相同的,在後臺接受的時候,用一個數組接受.而對於上傳固定的多個文件來說,就要遇到name值不同的情況.

接下來要討論的問題就是上傳固定多個文件,並且name值不相同的情況.

先看一下項目的結構吧:


步驟一:創建數據庫表:

CREATE TABLE uploadfile (
id INT(32) NOT NULL PRIMARY KEY AUTO_INCREMENT,
path VARCHAR(255)
);

步驟二:新建一個web project,引入struts2和hibernate(這些不細說)

步驟三:看一下index.jsp文件,就是文件選擇並提交的頁面:

<%@ page language="java" import="java.util.*" pageEncoding="utf-8"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head>
    <base href="<%=basePath%>">
    <title>upload test</title>
	<meta http-equiv="pragma" content="no-cache">
	<meta http-equiv="cache-control" content="no-cache">
	<meta http-equiv="expires" content="0">    
	<meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
	<meta http-equiv="description" content="This is my page">
  </head>
  <body>
    <form id="form1" name="form1" method="post" enctype="multipart/form-data"  action="upload.action">
<table bgcolor="#999999" width="700" border="0" cellspacing="1" cellpadding="0">
 <tr>
    <td height="35" align="left" bgcolor="#BBBBBB">
		文件一:<input type="file" name="upload1"/>
	</td>
	</tr>
	<tr>
    <td height="35" align="left" bgcolor="#BBBBBB">
		文件二:<input type="file" name="upload2"/>
	</td>
	</tr>
  <tr>
    <td height="35" align="left" bgcolor="#BBBBBB">
		<input type="submit" name="button" id="button" value="提交" />
	</td>
	</tr>
</table>
</form>
  </body>
</html>
注意,上面name分別設置了"upload1"和"upload2".
步驟四:配置struts.xml文件:

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE struts PUBLIC "-//Apache Software Foundation//DTD Struts Configuration 2.1//EN" "http://struts.apache.org/dtds/struts-2.1.dtd">
<struts>
<package namespace="/" name="" extends="struts-default">
<action name="upload" class="com.xingyunpi.action.UploadFile">
			<param name="savePath1">/upload1</param>
			<param name="savePath2">/upload2</param>
		 <result name="success">suc.jsp</result>
		</action>
		</package>
</struts>    

步驟五:用hibernate引入對數據庫的操作:EntityDao.java

package com.hibernate.data;

import org.hibernate.Session;
import org.hibernate.Transaction;

import com.hibernate.session.HibernateSessionFactory;

public class EntityDao {
	//獲取session
	public static Session getSession(){
		return HibernateSessionFactory.getSession();
	}
	
	public static void save(Uploadfile obj){
		Session se = getSession();
		Transaction tran = se.beginTransaction();//開始事物   
	    getSession().saveOrUpdate(obj);//執行   
	    tran.commit();//提交 
		se.close();
	}
	
}

步驟六:最主要的是action部分:

package com.xingyunpi.action;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.util.Date;

import org.apache.struts2.ServletActionContext;

import com.hibernate.data.EntityDao;
import com.hibernate.data.Uploadfile;
import com.opensymphony.xwork2.ActionSupport;

public class UploadFile extends ActionSupport {
	private java.io.File upload1; // 客戶端文件域  
    private String upload1ContentType; // 上傳的文件類型  
    private String upload1FileName; // 上傳的文件名  
      
    private java.io.File upload2; // 客戶端文件域  
    private String upload2ContentType; // 上傳的文件類型  
    private String upload2FileName; // 上傳的文件名  
    
    String savePath1;
    String savePath2;
    public String execute(){
    String fileName = "";//輸出流
    if(upload1!=null){
		String fileType = upload1FileName.substring(upload1FileName.lastIndexOf("."));
		fileName = (new Date().getTime()+0+1)+ fileType;
		
		//文件上傳
		FileOutputStream fos;
		try {
			//上傳到upload文件夾下
			fos = new FileOutputStream(ServletActionContext.getServletContext().getRealPath("upload") + "\\" + fileName);
			FileInputStream fis = new FileInputStream(upload1);
			byte[] buffer = new byte[1024];
			int len = 0;
			while ((len = fis.read(buffer)) > 0)
			{
				fos.write(buffer , 0 , len);
			}   
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (Exception e) {
			e.printStackTrace();
		}
		//存儲
		Uploadfile uf = new Uploadfile();
		uf.setPath("upload/" + fileName);
		EntityDao.save(uf);
		
	}//上面是上傳第一個圖片
	if(upload2!=null ){//文件
	String fileType = new String();
	fileType = upload2FileName.substring(upload2FileName.lastIndexOf("."));
	fileName = (new Date().getTime()+1+1)+ fileType;
//		文件上傳
	FileOutputStream fos;
	try {
		//上傳到upload文件夾下
		fos = new FileOutputStream(ServletActionContext.getServletContext().getRealPath("upload") + "\\" + fileName);
		FileInputStream fis = new FileInputStream(upload2);
		byte[] buffer = new byte[1024];
		int len = 0;
		while ((len = fis.read(buffer)) > 0)
		{
			fos.write(buffer , 0 , len);
		}   
	} catch (FileNotFoundException e) {
		e.printStackTrace();
	} catch (Exception e) {
		e.printStackTrace();
	}
	//存儲
	Uploadfile uf = new Uploadfile();
	uf.setPath("upload/" + fileName);
	EntityDao.save(uf);
	
	}//上傳第二個圖片
		return SUCCESS;
    }
    
    String getFilename(String name){
		   
		   /**
		    * 獲取文件名的後綴
		    * @return String
		    */
		   int i = name.lastIndexOf(".")+1;
		   	return name.substring(i,name.length());
	   }
	   
	
	public String getSavePath1() {
		return savePath1;
	}
	public void setSavePath1(String savePath1) {
		this.savePath1 = savePath1;
	}
	public String getSavePath2() {
		return savePath2;
	}
	public void setSavePath2(String savePath2) {
		this.savePath2 = savePath2;
	}
	public java.io.File getUpload1() {
		return upload1;
	}
	public void setUpload1(java.io.File upload1) {
		this.upload1 = upload1;
	}
	public String getUpload1ContentType() {
		return upload1ContentType;
	}
	public void setUpload1ContentType(String upload1ContentType) {
		this.upload1ContentType = upload1ContentType;
	}
	public String getUpload1FileName() {
		return upload1FileName;
	}
	public void setUpload1FileName(String upload1FileName) {
		this.upload1FileName = upload1FileName;
	}
	public java.io.File getUpload2() {
		return upload2;
	}
	public void setUpload2(java.io.File upload2) {
		this.upload2 = upload2;
	}
	public String getUpload2ContentType() {
		return upload2ContentType;
	}
	public void setUpload2ContentType(String upload2ContentType) {
		this.upload2ContentType = upload2ContentType;
	}
	public String getUpload2FileName() {
		return upload2FileName;
	}
	public void setUpload2FileName(String upload2FileName) {
		this.upload2FileName = upload2FileName;
	}
    
}

由此需要注意的是,jsp裏面配置的name和struts.xml中傳遞的param的name再加上action接受的"

private java.io.File upload1; // 客戶端文件域

"的命名是一樣的.

這樣,就能用struts2把不同name的文件名上傳到後臺


最後加上下載整個項目的程序:

FileUpload.rar

發佈了132 篇原創文章 · 獲贊 32 · 訪問量 30萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章