struts2中檔案的上傳與下載
阿新 • • 發佈:2018-12-15
upload.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> <%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%> <!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>檔案上傳</title> </head> <body> <form action="<%=request.getContextPath() %>/Action4_add" method="post" enctype="multipart/form-data"> <input type="file" name="ff"> <input type="submit" name="提交"> </form> </body> </html>
Action.java public class Action4 extends ActionSupport{ //檔案下載 private String nn; //上傳檔案 private File ff; //上傳檔名 private String ffFileName; //上傳檔案型別 private String ffContentType;
public String add() throws IOException { //System.out.println("sdf"); FileUtils.copyFile(ff, new File("f:"+File.separator+"a.jpg")); return "add"; } public String dd() { return "dd"; } public String getContextType() { return ServletActionContext.getServletContext().getMimeType(nn); } public String getDownloadFileName() throws UnsupportedEncodingException{ return new String(nn.getBytes("utf-8"),"iso8859-1"); } public InputStream getInputStream() throws IOException { nn=new String(nn.getBytes("iso8859-1"),"utf-8"); FileInputStream fis=new FileInputStream(new File("d:"+File.separator+nn)); return fis; } //************* public File getFf() { return ff; } public void setFf(File ff) { this.ff = ff; } public String getFfFileName() { return ffFileName; } public void setFfFileName(String ffFileName) { this.ffFileName = ffFileName; } public String getFfContentType() { return ffContentType; } public void setFfContentType(String ffContentType) { this.ffContentType = ffContentType; } public String getNn() { return nn; } public void setNn(String nn) { this.nn = nn; } }
struts.xml
<package name="default" namespace="/" extends="struts-default"> <interceptors> <interceptor name="interceptor1" class="com.baidu.interceptor.Interceptor1"> </interceptor> </interceptors> <action name="Action4_*" class="com.baidu.action.Action4" method="{1}"> <result name="add">/success.jsp</result> <result name="dd" type="stream"> <param name="contentType">${contentType}</param> <!-- 呼叫當前action中的getContentType()方法 --> <param name="contentDisposition">attachment;filename=${downloadFileName}</param> <param name="inputStream">${inputStream}</param><!-- 呼叫當前action中的getInputStream()方法 --> </result> <!-- 上傳時只限制action檔案的大小 --> <interceptor-ref name="defaultStack"> <param name="fileUpload.maximumSize">20</param> </interceptor-ref> </action> </package>