Struts2 實現多檔案上傳
阿新 • • 發佈:2019-01-06
前臺form 表單:設定method=post,enctype=multipart/form-data。
struts2在原有的上傳解析器繼承上做了進一步封裝,更進一步簡化了檔案上傳。
Action需要使用3個屬性來封裝該檔案域的資訊:
(1)型別為File的*屬性封裝了該檔案域對應的檔案內容;
(2)型別為String的***FileName屬性封裝了該檔案域對應的檔案的檔案型別;
(3)型別為String的***ContentType屬性封裝了該檔案域對應的檔案的型別。
具體實現:
新建web專案
新增struts2相關包
myeclipse可直接下載,右擊專案,如下。前臺
<%@ page language="java" import="java.util.*" pageEncoding="utf-8"%> <% String path = request.getContextPath(); String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/"; %> <html> <body> <form action="upload.action"
配置web.xml
<?xml version="1.0" encoding="UTF-8"?> <web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
配置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> <constant name="struts.enable.DynamicMethodInvocation" value="false"/> <constant name="struts.devMode" value="true"/> <constant name="struts.multipart.saveDir" value="/tmp"/> <constant name="struts.custom.i18n.resources" value="app"></constant> <package name="default" namespace="/" extends="struts-default"> <action name="upload" class="com.yf.action.UploadAction"> <result>/index.jsp</result> <interceptor-ref name="defaultStack"></interceptor-ref> </action> </package> </struts>
- 後臺程式碼
public class UploadAction extends ActionSupport{
private List<File> upload;
private List<String> uploadContentType;
private List<String> uploadFileName;
public List<File> getUpload() {
return upload;
}
public void setUpload(List<File> upload) {
this.upload = upload;
}
public List<String> getUploadContentType() {
return uploadContentType;
}
public void setUploadContentType(List<String> uploadContentType) {
this.uploadContentType = uploadContentType;
}
public List<String> getUploadFileName() {
return uploadFileName;
}
public void setUploadFileName(List<String> uploadFileName) {
this.uploadFileName = uploadFileName;
}
@Override
public String execute() throws Exception {
//檔案儲存路徑
String path = ServletActionContext.getServletContext().getRealPath("/images");
File file = new File(path);
//不存在則建立
if(!file.exists()){
file.mkdir();
}
//迴圈將檔案上傳到指定路徑
for(int i = 0; i< upload.size(); i++){
FileUtils.copyFile(upload.get(i), new File(file,uploadFileName.get(i)));
}
return SUCCESS;
}
結果如下