TA的每日心情 | 开心 2021-12-13 21:45 |
---|
签到天数: 15 天 [LV.4]偶尔看看III
|
index.jsp
<%@ page language="java" pageEncoding="GB18030"%>
<%@ taglib uri="http://struts.apache.org/tags-bean" prefix="bean"%>
<%@ taglib uri="http://struts.apache.org/tags-html" prefix="HTML"%>
<%@ taglib uri="http://struts.apache.org/tags-logic" prefix="logic"%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html:html lang="true">
<head>
<html:base />
<title>Struts批量上传</title>
<script>
i=1;
function addItem()
{
document.getElementById('uploadFile').innerHTML+='<input type=\"file\" name=\"files('+i+')\"><br/> ';
i++;
}
</script>
</head>
<body>
<html:form action="contentPublish.do" enctype="multipart/form-data">
<html:file property="files(0)" />
<html:errors property="files" />
<div id="uploadFile"></div>
<input type="button" value="上传更多" />
<html:submit value="批量上传"/>
</html:form>
</body>
</html:html>
ActionForm代码:
public class ContentPublishForm extends ActionForm {
private List<FormFile> files = new ArrayList<FormFile>();
public List<FormFile> getFiles() {
return files;
}
public void setFiles(List<FormFile> files) {
this.files = files;
}
}
Action 代码:
public class ContentPublishAction extends Action {
public ActionForward execute(ActionMapping mapping, ActionForm form,
HttpServletRequest request, HttpServletResponse response) throws IOException {
ContentPublishForm contentPublishForm = (ContentPublishForm) form;// TODO
MultipartRequestHandler multipartRequestHandler = form
.getMultipartRequestHandler();
// 取得所有上传文件的对象集合
Hashtable elements = multipartRequestHandler.getFileElements();
// 循环遍历每一个文件
Collection values = elements.values();
int count = values.size();
response.setCharacterEncoding("GBK");
PrintWriter out = response.getWriter();
int k = 0;
for (java.util.Iterator i = values.iterator(); i.hasNext();) {
FormFile file = (org.apache.struts.upload.FormFile) i.next();// 取得上传的文件
if ("" != file.toString()) {
FileOutputStream fileOutput;
try {
String fileUrl = this.getServlet().getServletContext()
.getRealPath("//image//" + file.getFileName());
fileOutput = new FileOutputStream(fileUrl);
fileOutput.write(file.getFileData());
fileOutput.flush();
fileOutput.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
out.println("成功上传:"+count+"个文件<br/>");
return null;
}
} |
|