標籤:pack error 檔案大小 form this tag filename 設定檔 art
一、Struts2檔案上傳:
二、設定檔的大小以及允許上傳的檔案類型:
三、大檔案上傳:
如果不配置上傳檔案的大小,struts2預設允許上傳檔案最大為2M; 2097152Byte; 例子實現:
com.cy.action.FileUploadAction.java:
package com.cy.action;import java.io.File;import org.apache.commons.io.FileUtils;import com.opensymphony.xwork2.ActionSupport;public class FileUploadAction extends ActionSupport{ private static final long serialVersionUID = 1L; private File struts; //檔案,對應fileupload.jsp中input type=file的name private String strutsFileName; //檔案名稱 private String strutsContentType; //檔案類型 public File getStruts() { return struts; } public void setStruts(File struts) { this.struts = struts; } public String getStrutsFileName() { return strutsFileName; } public void setStrutsFileName(String strutsFileName) { this.strutsFileName = strutsFileName; } public String getStrutsContentType() { return strutsContentType; } public void setStrutsContentType(String strutsContentType) { this.strutsContentType = strutsContentType; } @Override public String execute() throws Exception { System.out.println("檔案名稱:" + strutsFileName); System.out.println("檔案類型:" + strutsContentType); String filePath = "E:/" + strutsFileName; File savefile = new File(filePath); FileUtils.copyFile(struts, savefile); return SUCCESS; } }
struts.xml:
<?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> <!-- 配置允許上傳檔案最大為20000000Byte,約20Mb --> <constant name="struts.multipart.maxSize" value="20000000"></constant> <package name="manage" extends="struts-default"> <action name="upload" class="com.cy.action.FileUploadAction"> <result name="input">fileupload.jsp</result> <result name="success">success.jsp</result> <!-- 配置允許上傳的檔案類型 配置允許上傳的檔案大小,最大81101byte,= 79.2KB --> <interceptor-ref name="fileUpload"> <param name="allowedTypes">image/bmp,image/x-png,image/gif,image/jpg,image/jpeg</param> <param name="maximumSize">81101</param> </interceptor-ref> <interceptor-ref name="defaultStack"></interceptor-ref> </action> </package> </struts>
fileupload.jsp:
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%><%@taglib prefix="s" uri="/struts-tags" %><!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"><html><head><meta http-equiv="Content-Type" content="text/html; charset=UTF-8"><title>Insert title here</title></head><body> <!-- 顯示檔案上傳錯誤時,返回的失敗資訊 --> <s:fielderror></s:fielderror> <form action="upload" method="post" enctype="multipart/form-data"> 選擇檔案:<input type="file" name="struts" /><br/> <input type="submit" value="提交" /> </form></body></html>
success.jsp:
<body>檔案上傳成功!</body>
View Code
測試結果:
1)配置允許上傳的檔案類型,和檔案大小;
2)配置大檔案上傳,上面例子中配置了20M左右;
如果不配置大檔案上傳,上傳大於2M的會報錯:
------------
struts2學習(13)struts2檔案上傳和下載(1)