選擇多個文件上傳 html
後臺控制檯信息 java
@建立一個名爲「struts_file」的webProject web
@引入struts必須包 apache
<?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>
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; // } }
<%@ 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>