package org.zln.struts.domain;
import org.apache.struts.upload.FormFile;
/**
* Created by sherry on 000021/5/21 21:06.
*/
public class RegUser {
/*文件上传*/
private FormFile photo;
public FormFile getPhoto() {
return photo;
}
public void setPhoto(FormFile photo) {
this.photo = photo;
}
}
<%@ taglib prefix="html" uri="http://struts.apache.org/tags-html" %>
<%@ page contentType="text/html;charset=UTF-8" language="java" pageEncoding="UTF-8" %>
<html>
<head>
<title>注册用户</title>
</head>
<body>
<html:form action="/upload" method="post" enctype="multipart/form-data">
<table>
<caption><h2>文件上传</h2></caption>
<tr>
<td>文件</td>
<td>
<html:file property="regUser.photo"/>
</td>
</tr>
<tr>
<td colspan="2" align="center">
<html:submit>
<bean:message key="info.submit" bundle="message"/>
</html:submit>
</td>
</tr>
</table>
</html:form>
</body>
</html>
package org.zln.struts.action;
import org.apache.commons.lang3.StringUtils;
import org.apache.struts.Globals;
import org.apache.struts.action.*;
import org.apache.struts.upload.FormFile;
import org.zln.struts.domain.Gender;
import org.zln.struts.domain.Speciality;
import org.zln.struts.form.RegUserForm;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.*;
import java.util.ArrayList;
import java.util.List;
import java.util.Locale;
import java.util.UUID;
/**
* Created by coolkid on 2015/5/23 0023.
*/
public class UserAction extends Action {
......
private String upload(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws IOException {
RegUserForm regUserForm = (RegUserForm) form;
FormFile photo = regUserForm.getRegUser().getPhoto();
System.out.println(photo.getFileName()+
":"+photo.getFileSize());
//response.setContentType("text/html;charset=UTF-8");//过滤器已经做了这活儿
/*response.getWriter().print(photo.getFileName() +
":" + photo.getFileSize());*/
InputStream inputStream = photo.getInputStream();
String savePath = request.getServletContext().getRealPath("/upLoad");
File upDir = new File(savePath);
if (!upDir.exists()){
upDir.mkdirs();
System.out.println(savePath+"\n目录创建成功");
}
System.out.println("path:"+savePath);
BufferedOutputStream bufferedOutputStream = new BufferedOutputStream(new FileOutputStream(new File(upDir, UUID.randomUUID()+photo.getFileName())));
byte[] bytes = new byte[1024];
int len;
while ((len = inputStream.read())>0){
bufferedOutputStream.write(bytes,0,len);
}
bufferedOutputStream.close();
inputStream.close();
System.out.println("文件上传成功");
return "SUCCESS";
}
......
}