在upload.jsp頁面中將多個文件域對象命名為相同的名字,這樣在action中就可以將多個文件域解析成一個數組,數組的大小就是文件域的個數,同時一個文件域解析成三個對應的變量,因此多個文件域對應三個數組,其中每個數組的大小就是文件域的個數。jsp頁面代碼如下:
</form>
對應的Action依次遍歷所有文件域,然后生成對應的輸入文件流,輸出文件流在指定的服務器保存路徑中添加對應的輸出文件流保存文件。同時動態指定服務器上文件的 保存路徑。
action代碼如下:
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import org.apache.struts2.ServletActionContext;
import com.opensymphony.xwork2.ActionSupport;
public class UploadAction extends ActionSupport {
private String title;
private File[] upload;
private String[] uploadFileName;
private String[] uploadContentType;
private String savePath;
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public File[] getUpload() {
return upload;
}
public void setUpload(File[] upload) {
this.upload = upload;
}
public String[] getUploadFileName() {
return uploadFileName;
}
public void setUploadFileName(String[] uploadFileName) {
this.uploadFileName = uploadFileName;
}
public String[] getUploadContentType() {
return uploadContentType;
}
public void setUploadContentType(String[] uploadContentType) {
this.uploadContentType = uploadContentType;
}
public String getSavePath() {
return ServletActionContext.getRequest().getRealPath(savePath);
}
public void setSavePath(String savePath) {
this.savePath = savePath;
}
public String upload()throws Exception{
File[] files=this.getUpload();
for(int i=0;i<files.length;i++){
FileOutputStream fos=new FileOutputStream(this.getSavePath()+"http://"+this.getUploadFileName()[i]);
byte[] buffer=new byte[1024];
FileInputStream fis=new FileInputStream(files[i]);
int len=0;
while((len=fis.read(buffer))>0){
fos.write(buffer,0,len);
}
}
return SUCCESS;
}
}
struts.xml文件配置如下:配置文件上傳的攔截器,允許 的上傳文件類型,上傳文件大小限制,同時引入defaultStack攔截器和上傳文件在服務器上的保存位置
</struts>
success.jsp頁面代碼如下:
|
新聞熱點
疑難解答