struts2——多文件上传

图片演示

选择多个文件上传struts2——多文件上传_第1张图片

后台控制台信息

struts2——多文件上传_第2张图片


注意事项

@创建一个名为“struts_file”的webProject

@引入struts必须包


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>

 <!-- 上传限制 2G左右-->
    <constant name="struts.multipart.maxSize" value="2110701096"/>
 
 <package name="up" namespace="/up" extends="struts-default">
 <action name="uploadAction" class="com.web.action.UploadAction">
 <result name="success">/message.jsp</result>
 <result name="error">/error.jsp</result>
 </action> 
 </package>

</struts>  

Java代码(Action)

package com.web.action;

import java.io.BufferedInputStream;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import javax.servlet.http.HttpServletResponse;
import org.apache.struts2.ServletActionContext;
import com.opensymphony.xwork2.ActionSupport;


public class DownloadAction extends ActionSupport{


 private String fileName;
 
 public InputStream getInputStream() throws UnsupportedEncodingException,FileNotFoundException{
 
 HttpServletResponse response=ServletActionContext.getResponse();
 
 //attachment,以附件的方式下载文件,会打开保存文件对话框;
 //inline,以内联的方式下载,浏览器会直接打开文件 
 response.setHeader("content-Disposition", "attachment;fileName="+
 java.net.URLEncoder.encode(fileName,"UTF-8"));
 
 //如果fileName是相对路径
 ServletActionContext.getServletContext().getResourceAsStream(fileName);
 
 //如果fileName是绝对路径
 return new BufferedInputStream(new FileInputStream(fileName));
 
 }


 @Override
 public String execute() throws Exception {
 return SUCCESS;
 }
 
 
 public String getFileName() {
 return fileName;
 }
 
 public void setFileName(String fileName) throws UnsupportedEncodingException{
 //用UTF-8重新编码文件名,解决中文乱码
 this.fileName=new String(fileName.getBytes("ISO-8859-1"),"UTF-8");
 }


//	public void setFileName(String fileName){
//		this.fileName = fileName;
//	} 
}

JSP代码

<%@ page language="java" import="java.util.*" pageEncoding="utf-8"%>
<%@taglib uri="/struts-tags" prefix="s" %>


<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head>
    <title>struts2——多文件上传</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>
  
  	<s:form namespace="/up" action="uploadAction" method="post" enctype="multipart/form-data">
  		<s:file name="image" label="请选择文件!" multiple="multiple"></s:file>
  		<s:submit label="上传"></s:submit>
  	</s:form></body>
</html>


测试地址: http://localhost:8080/struts_file/index.jsp

你可能感兴趣的:(Struts2多文件上传)