struts2实现多文件上传

参照struts2官网的例子做了一个用struts2实现多文件上传的例子,这里是上传图片文件。
  • 所需要应用的包
struts2实现多文件上传
  • 页面
上传页面multiFileUpload.jsp,一次上传3个文件
<%@ page language="java" contentType="text/html; charset=utf-8"	pageEncoding="utf-8"%>
<%@ taglib prefix="s" uri="/struts-tags"%>

<!DOCTYPE html PUBLIC "-//W3C//DTDXHTML1.0Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
	<title>Struts2FileUpload</title>
</head>
<body>
	<s:form action="multiUpload" method="POST" enctype="multipart/form-data">
		<s:file label="File(1)" name="upload" />
	    <s:file label="File(2)" name="upload" />
	    <s:file label="FIle(3)" name="upload" /> 
		<s:submit />
	</s:form>
</body>
</html>

ShowUploadMore.jsp上传成功页面,imageFileName[0]为取数组值(图片名称),与java后台对应,页面通过取得图片地址显示上传后的图片
<%@ page language="java" contentType="text/html; charset=utf-8"	pageEncoding="utf-8"%>
<%@ taglib prefix="s" uri="/struts-tags"%>

<!DOCTYPE html PUBLIC "-//W3C//DTDXHTML1.0Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <title> Struts 2 File Upload </title>
</head>
<body>
    <div style="padding:3px; border:solid 1px #cccccc; text-align:center">
        <img src ='UploadImages/<s:property value ="imageFileName[0]" />'/>
        <img src ='UploadImages/<s:property value ="imageFileName[1]" />'/>
        <img src ='UploadImages/<s:property value ="imageFileName[2]" />'/>
        <br />
        <s:property value ="caption" />
    </div>
</body>
</html>

  • action类MultiFileUploadAction.java,处理三个上传的图片文件,用数组实现。在工程下(WebRoot下)新建一个UploadImages文件夹,用于存放上传的图片
package com.tutorial;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Date;

import org.apache.struts2.ServletActionContext;

import com.opensymphony.xwork2.ActionSupport;

public class MultiFileUploadAction extends ActionSupport {
	private static final long serialVersionUID = 572146812454l;
	private static final int BUFFER_SIZE = 16 * 1024;

	/*
	 * 多文件上传(图片)
	 */
	private String[] imageFileName = new String[3];

	private File[] uploads;
	private String[] uploadFileNames;
	private String[] uploadContentTypes;
	
	public String[] getImageFileName() {
	    return imageFileName;
	  }

	public File[] getUpload() {
		return this.uploads;
	}

	public void setUpload(File[] upload) {
		this.uploads = upload;
	}

	public String[] getUploadFileName() {
		return this.uploadFileNames;
	}

	public void setUploadFileName(String[] uploadFileName) {
		this.uploadFileNames = uploadFileName;
	}

	public String[] getUploadContentType() {
		return this.uploadContentTypes;
	}

	public void setUploadContentType(String[] uploadContentType) {
		this.uploadContentTypes = uploadContentType;
	}

	private static void copy(File src, File dst) {
		try {
			InputStream in = null;
			OutputStream out = null;
			try {
				in = new BufferedInputStream(new FileInputStream(src),
						BUFFER_SIZE);
				out = new BufferedOutputStream(new FileOutputStream(dst),
						BUFFER_SIZE);
				byte[] buffer = new byte[BUFFER_SIZE];
				while (in.read(buffer) > 0) {
					out.write(buffer);
				}
			} finally {
				if (null != in) {
					in.close();
				}
				if (null != out) {
					out.close();
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	private static String getExtention(String fileName) {
		int pos = fileName.lastIndexOf(".");
		return fileName.substring(pos);
	}

	@Override
	public String execute() {
		int i = 0;
		for(String fileName:uploadFileNames){
			imageFileName[i] = new Date().getTime()+i + getExtention(fileName);
			File imageFile = new File(ServletActionContext.getServletContext()
					.getRealPath("/UploadImages")
					+ "/" + imageFileName[i]);
			copy(uploads[i++], imageFile); //写文件到UploadImages文件夹
		}
		return SUCCESS;
	}
}

  • 配置文件
struts.xml文件,该文件放在类输出路径下(struts2默认初始化加载),这里放在src下
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE struts PUBLIC "-//Apache Software Foundation//DTD Struts Configuration 2.0//EN"
    "http://struts.apache.org/dtds/struts-2.0.dtd" >

<struts>
   <constant name="struts.custom.i18n.resources" value="uploadMessage"/>
   <package name="fileUploadDemo" extends="struts-default">
       
       <action name="multiUpload" class="com.tutorial.MultiFileUploadAction">
           <interceptor-ref name="fileUploadStack"/>
           <result name="success">/ShowUploadMore.jsp</result>
           
           <!-- 多文件上传 -->
       </action>
   </package>
</struts>

web.xml文件,主要是配置struts2的过滤器
<?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.4" 
	xmlns="http://java.sun.com/xml/ns/j2ee" 
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
	xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee 
	http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd">
  
   <display-name>Struts 2 Fileupload</display-name>

    <filter>
        <filter-name>struts-cleanup</filter-name >
        <filter-class>
            org.apache.struts2.dispatcher.ActionContextCleanUp
        </filter-class >
    </filter>
    
     <filter>
        <filter-name>struts2</filter-name>
        <filter-class>
            org.apache.struts2.dispatcher.FilterDispatcher
        </filter-class>
    </filter>	    
    
    <filter-mapping>
        <filter-name>struts-cleanup</filter-name>
        <url-pattern>/*</url-pattern>
    </filter-mapping>

    <filter-mapping>
        <filter-name>struts2</filter-name>
        <url-pattern>/*</url-pattern>
    </filter-mapping>

    <welcome-file-list>
        <welcome-file>index.jsp</welcome-file>
    </welcome-file-list>
  
</web-app>


启动服务,访问http://localhost:8080/struts2upload/multiFileUpload.jsp即可看到效果。

你可能感兴趣的:(java,apache,xml,jsp,struts)