日期:2014-05-18 浏览次数:20682 次
<s:form action="UploadHeadAction" method="post" enctype="multipart/form-data" >
<s:file name="txtImg" id="txtImg" ></s:file>
<span class="redcolor">最佳图片尺寸:宽度不超过600像素,高度不超过600像素.大小不超过2MB[jpeg|jpg|gif|png]</span>
<s:submit id="btnUploadImg" ></s:submit>
</s:form>
import java.util.Iterator;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.io.File;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import jobs.pojo.PersonalDB;
import com.opensymphony.xwork2.ActionSupport;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.apache.struts2.ServletActionContext;
public class UploadHeadAction extends ActionSupport {
// 获取Request
private HttpServletRequest getRequest() {
HttpServletRequest request = ServletActionContext.getRequest();
return request;
}
// 获取Session
private HttpSession getSession() {
return getRequest().getSession();
}
// 对文件名进行重写
private String getFileName(String name) {
// 匹配文件后缀.
String lastname = "";
Pattern p = Pattern.compile("\\.(jpeg|jpg|gif|png)$");
Matcher m = p.matcher(name);
while (m.find()) {
lastname = m.group();
}
// 随机生成文件名.
String user = (String) getSession().getAttribute("user");
long time = System.currentTimeMillis();
String filename = user + "-" + time + "" + lastname;
System.out.println(filename + "--0");
return filename;
}
// 上传主方法.
public void upload() {
//System.out.println(System.currentTimeMillis());
setHeadpath("./upload");
File folder = new File(getHeadpath());
if (!folder.exists())
folder.mkdirs();
String message = null;
//System.out.println(0010104);
boolean choose = ServletFileUpload.isMultipartContent(getRequest());
System.out.println("choose->"+choose);
if (choose) { // 判断是否获取的是文件
//System.out.println(01);
DiskFileItemFactory disk = new DiskFileItemFactory();
disk.setSizeThreshold(20 * 1024); // 设置内存可存字节
disk.setRepository(disk.getRepository()); // 设置临时文件目录
ServletFileUpload up = new ServletFileUpload(disk);
int maxsize = 2 * 1024 * 1024;
List list = null;
try {
list = up.parseRequest(getRequest()); // 获取上传列表
System.out.println(00001);
} catch (Exception e) {
e.printStackTrace();
}
Iterator