感动中国十大人物老师:Struts 2上传文件小谈

来源:百度文库 编辑:中财网 时间:2024/05/09 07:46:18
下面谈谈Struts 2框架的文件上传应用
(1)原理:Struts 2框架没有提供文件上传的解析器(也可以说没有提供自己的文件上传组件),它是借助于其他文件上传组件。例如,Struts 2默认的使用Jakarta的commons-fileupload.jar和commons-io.jar。但Struts 2在原有的上传解析器中做了更进一步的封装,更进一步简化上传文件。
(2)首先,在struts.properties文件中配置Struts 2上传文件的解析器
#默认的使用Jakarta的commons-fileupload文件解析器
struts.multipart.parser = jakarta
(3)在WEB-INF/lib中加入两个包,commons-fileupload.jar和commons-io.jar。
(4)编写实现文件上传的Action类,代码如下:
package com.gxa.edu.struts2.ch4.action;
/**
* 利用Struts 2实现文件上传功能
* @author Administrator
*
*/
import java.io.File;
import java.io.FileOutputStream;
import java.io.FileInputStream;
import org.apache.struts2.ServletActionContext;
public class FileUploadAction {

private File fileUpload;//获取上传文件
private String fileUploadContentType;//获取上传文件的类型,注意上传类型变量命名方式
private String fileUploadFileName;//获取上传文件的名称
private String fileSavePath;//设置上传文件的保存路径,利用struts2框架的设置注入。在struts.xml文件配置关键字
public String getFileSavePath() {
  return ServletActionContext.getServletContext().getRealPath(fileSavePath);
}
public void setFileSavePath(String fileSavePath) {
  this.fileSavePath = fileSavePath;
}
public File getFileUpload() {
  return fileUpload;
}
public void setFileUpload(File fileUpload) {
  this.fileUpload = fileUpload;
}
public String getFileUploadContentType() {
  return fileUploadContentType;
}
public void setFileUploadContentType(String fileUploadContentType) {
  this.fileUploadContentType = fileUploadContentType;
}
public String getFileUploadFileName() {
  return fileUploadFileName;
}
public void setFileUploadFileName(String fileUploadFileName) {
  this.fileUploadFileName = fileUploadFileName;
}

public String upload() throws Exception {
  System.out.println("===利用struts2上传文件===");
  System.out.println("文件类型===" + this.fileUploadContentType);
  FileInputStream fis = new FileInputStream(getFileUpload());
  File file = new File(getFileSavePath().replaceAll("[url=]\\\\[/url]", "/"));
  if (!file.exists()) {
   file.mkdirs();
  }
  FileOutputStream fos = new FileOutputStream(getFileSavePath().replaceAll("[url=]\\\\[/url]", "/") + "/" + getFileUploadFileName());
  int i = 0;
  byte[] buf = new byte[1024];
  while ((i = fis.read(buf)) != -1) {
   fos.write(buf, 0, i);
  }
  return "success";
}
}
(5)编写一个upload.jsp文件,代码如下:
<%@ page language="java" pageEncoding="GBK"%>
<%@ taglib prefix = "s" uri = "/struts-tags" %>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>


  
   
   
    My JSP 'upload.jsp' starting page
   


   



  

  
    This is the FileUpload of Struts 2 page.

   
     
     
   
  

(6)配置struts-fileupload.xml文件,代码如下:

    "-//Apache Software Foundation//DTD Struts Configuration 2.0//EN"
    "http://struts.apache.org/dtds/struts-2.0.dtd">
   




  
   /upload
   /ch4/upload.jsp
   /ch4/upload.jsp