標籤:struts2 檔案上傳
在web項目中,檔案上傳、頭像上傳這樣的功能經常是要用到的,下面就以在struts2中實現檔案上傳功能為例子,簡單地理一下檔案上傳功能的編碼思路。
項目目錄結構
項目原始碼
web.xml
<?xml version="1.0" encoding="UTF-8"?><web-app version="3.0" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"> <filter> <filter-name>struts 2</filter-name> <filter-class>org.apache.struts2.dispatcher.FilterDispatcher</filter-class> </filter> <filter-mapping> <filter-name>struts 2</filter-name> <url-pattern>/*</url-pattern> </filter-mapping> <welcome-file-list> <welcome-file>index.jsp</welcome-file> </welcome-file-list> </web-app>
struts.xml
<span style="font-size:12px;"><?xml version="1.0" encoding="UTF-8"?><!DOCTYPE struts PUBLIC "-//Apache Software Foundation//DTD Struts Configuration 2.3//EN" "http://struts.apache.org/dtds/struts-2.3.dtd"> <struts> <package name="default" extends="struts-default"> <action name="upload" class="com.upload.action.UploadAction" method="upload"> <result name="success">/success.jsp</result> <result name="error">/upload.jsp</result> </action> </package></struts></span>
UploadAction.java
package com.upload.action;import java.io.File;import java.io.FileInputStream;import java.io.FileOutputStream;import java.io.InputStream;import java.io.OutputStream;import java.util.UUID;import javax.servlet.ServletContext;import org.apache.struts2.ServletActionContext;import com.opensymphony.xwork2.ActionContext;import com.opensymphony.xwork2.ActionSupport;public class UploadAction extends ActionSupport{private File upload; //上傳檔案private String uploadFileName; //上傳的檔案名稱public File getUpload(){ return upload;}public void setUpload(File upload){this.upload = upload;}public String getUploadFileName(){return uploadFileName;}public void setUploadFileName(String uploadFileName){this.uploadFileName = uploadFileName;}public String upload() throws Exception{//如果選擇了上傳功能,則執行上傳操作;否則,不作任何操作if(getUpload() != null){//根據上傳的檔案得到輸入資料流InputStream is = new FileInputStream(getUpload());//更改上傳檔案名稱為:隨機數+上傳檔案名稱setUploadFileName(UUID.randomUUID().toString()+ getUploadFileName());//指定輸出資料流地址,此處是輸出到伺服器項目的根目錄下的images/userPhoto下OutputStream os = new FileOutputStream(getWebRootPath() + "images\\userPhoto\\" + getUploadFileName());byte buffer[] = new byte[1024];int count = 0;//把檔案寫到指定位置的檔案中while((count = is.read(buffer)) > 0){os.write(buffer, 0, count);}//關閉輸出資料流對象os.close();//關閉輸入資料流對象is.close();//返回return SUCCESS;}else {return ERROR;}}/** * 獲得web項目根目錄 */public String getWebRootPath() throws Exception {ActionContext actionContext = ActionContext.getContext();ServletContext servletContext = (ServletContext)actionContext.get(ServletActionContext.SERVLET_CONTEXT);String rootPath = servletContext.getRealPath("/");return rootPath;}}<strong></strong>
upload.jsp
<span style="font-size:12px;"><%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%><%@ taglib uri="/struts-tags" prefix="s" %><%String path = request.getContextPath();String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";%><!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"><html> <head> <base href="<%=basePath%>"> <title>檔案上傳</title> </head> <body> <s:form action="upload.action" method="post" enctype="multipart/form-data"> <label for="photoPath">頭像:</label> <input type="text" id="photoPath" disabled="disabled"/> <input type="button" onclick="myfile.click();" value="選擇圖片" id="select"/><br /> <input type="file" id="myfile" name="upload" onchange="photoPath.value=this.value" style="display:none" /> <input type="submit" value="上傳" /> </s:form> </body></html></span><strong style="font-size:14px;"></strong>
success.jsp
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%><!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"><html> <head> <title>上傳成功</title> </head> <body> 恭喜您,檔案上傳成功!點<a href="upload.jsp">這裡</a>回去 </body></html>
上面的方法不僅可用於上傳圖片類型,也適用於其他檔案類型的上傳。
注意: Struts 2上傳檔案的預設大小限制是2MB,所以在測試的時候檔案不能太大,最好找個小的檔案。 如果要修改預設大小,只需要在Struts 2的struts.properties或struts.xml中修改struts.multipart.maxSize的值,如struts.multipart.maxSize=1024表示上傳檔案的總大小不能超過1KB 。
如在struts.xml中設定上傳的檔案大小不超過50MB,可以在struts.xml的<struts> </struts>標籤裡面添加:
<constant name="struts.multipart.maxSize" value="51200"/>
struts2中實現檔案上傳功能