一、配置web.xml. html
<?xml version="1.0" encoding="UTF-8"?>java
<web-app version="2.5" web
xmlns="http://java.sun.com/xml/ns/javaee" apache
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 服務器
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee app
http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">jsp
<welcome-file-list>post
<welcome-file>/index.jsp</welcome-file>this
</welcome-file-list>url
<filter>
<filter-name>struts2</filter-name>
<filter-class>
org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter
</filter-class>
</filter>
<filter-mapping>
<filter-name>struts2</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
</web-app>
二、配置struts2.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.custom.i18n.resources" value="globalMessages"/>
<constant name="struts.i18n.encoding" value="utf-8"/>
<!-- 服務器指定一個臨時的路徑 不然會上傳失敗 -->
<constant name="struts.multipart.saveDir" value="D:/test"/>
<constant name="struts.multipart.maxSize" value="30000000"></constant>
<package name="lee" extends="struts-default" namespace="/p">
<action name="file" class="com.cn.action.FileUpload" method="upload">
<interceptor-ref name="fileUpload">
<!--<param name="allowedTypes">application/zip,application/octet-stream</param>-->
<param name="maximumSize">524288000</param>
</interceptor-ref>
<interceptor-ref name="defaultStack"/>
<!-- 保存路徑爲當前項目WebRoot/upload -->
<param name="savePath" >/upload</param>
<result name="success">index.jsp</result>
</action>
</package>
</struts>
三、fileUpload 爲action類
package com.cn.action;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.PrintWriter;
import java.text.DecimalFormat;
import org.apache.struts2.ServletActionContext;
import com.opensymphony.xwork2.ActionSupport;
public class FileUpload extends ActionSupport {
private String savePath;
/**這裏的名字和html的名字必須對稱*/
private File img;
/**要上傳的文件類型*/
private String imgContentType;
/**文件的名稱*/
private String imgFileName;
/**
* 指定的上傳類型 zip 和 圖片格式的文件
*/
private static final String[] types = { "application/x-zip-compressed",
"ZIP", "image/pjpeg","image/x-png" }; //"application/octet-stream; charset=utf-8",
/***
* 判斷文件的類型是否爲指定的文件類型
* @return
*/
public boolean filterType() {
boolean isFileType = false;
String fileType = getImgContentType();
System.out.println(fileType);
for (String type : types) {
if (type.equals(fileType)) {
isFileType = true;
break;
}
}
return true;
}
public String getSavePath() {
String realPath = ServletActionContext.getRequest().getRealPath(savePath);
System.out.println("savePaht -- " + realPath);
return realPath;
}
public File getImg() {
return img;
}
public String getImgFileName() {
return imgFileName;
}
public void setSavePath(String value) {
this.savePath = value;
}
public void setImgFileName(String imgFileName) {
this.imgFileName = imgFileName;
}
public void setImg(File img) {
this.img = img;
}
public String getImgContentType() {
return imgContentType;
}
public void setImgContentType(String imgContentType) {
this.imgContentType = imgContentType;
}
/**
* 取得文件夾大小
*
* @param f
* @return
* @throws Exception
*/
public long getFileSize(File f) throws Exception {
return f.length();
}
public String FormetFileSize(long fileS) {// 轉換文件大小
DecimalFormat df = new DecimalFormat("#.00");
String fileSizeString = "";
if (fileS < 1024) {
fileSizeString = df.format((double) fileS) + "B";
} else if (fileS < 1048576) {
fileSizeString = df.format((double) fileS / 1024) + "K";
} else if (fileS < 1073741824) {
fileSizeString = df.format((double) fileS / 1048576) + "M";
} else {
fileSizeString = df.format((double) fileS / 1073741824) + "G";
}
return fileSizeString;
}
/**
* 上傳文件操做
*
* @return
* @throws Exception
*/
public String upload() throws Exception {
String ct = ServletActionContext.getRequest().getHeader("Content-Type");
System.out.println("Content-Type="+ct);
String result = "unknow error";
System.out.println("orderId="+getOrderId());
PrintWriter out = ServletActionContext.getResponse().getWriter();
if (!filterType()) {
System.out.println("文件類型不正確");
ServletActionContext.getRequest().setAttribute("typeError",
"您要上傳的文件類型不正確");
result = "error:" + getImgContentType() + " type not upload file type";
} else {
System.out.println("當前文件大小爲:"
+ FormetFileSize(getFileSize(getImg())));
FileOutputStream fos = null;
FileInputStream fis = null;
try {
// 保存文件那一個路徑
fos = new FileOutputStream(getSavePath() + "\\"
+ getImgFileName());
fis = new FileInputStream(getImg());
byte[] buffer = new byte[1024];
int len = 0;
while ((len = fis.read(buffer)) > 0) {
fos.write(buffer, 0, len);
}
//result = "上傳成功!";
result = "Upload File Success !";
} catch (Exception e) {
result = "Upload File Failed ! ";
e.printStackTrace();
} finally {
fos.close();
fis.close();
}
}
out.print(result);
return null;
}
}
四、jsp頁面
<form action="p/file!upload" method="post" enctype="multipart/form-data">
選擇文件:
<input type="file" name="img" />
<br>
<input type="submit" value="上傳" />
</form>