UploadForm上传一个form中的多个file

苦苦的潜行者 2011-09-14 04:16:22
先上图


在一个form里面实现两个文件的不同时上传,两个上传互不干涉.

之前只有一个file 和submit,即Select Excel File那一行;现在我加上了下面的Feedback File 一行file和submit.
结果导致只能Feedback这个submit能够上传文件,Select那一行的submit一上传就出错,说是The input file was not found.
然后我后台输出Select一行的file.getFileName()为空.这是为什么呢!

上代码

这是form体
<html:form action="uploadAction.do?method=upFile"
enctype="multipart/form-data">
<c:choose>
<c:when test="${zn == 'pilot'}">
<input type="radio" name="name" value="pilot"
checked="checked" onclick="getZoneDate('pilot');"/>
<font color="red">PRFQ1</font>
</c:when>
<c:otherwise>
<input type="radio" name="name" value="pilot" onclick="getZoneDate('pilot');"/>
<font color="red">PRFQ1</font>
</c:otherwise>
</c:choose>
<c:choose>
<c:when test="${zn == 'week'}">
<input type="radio" name="name" value="week"
checked="checked" onclick="getZoneDate('week');"/>
<font color="red">PRFQ2</font>
</c:when>
<c:otherwise>
<input type="radio" name="name" value="week" onclick="getZoneDate('week');"/>
<font color="red">PRFQ2</font>
</c:otherwise>
</c:choose>
<br/>
Select Excel File:<html:file property="theFile" />  
<html:submit value="upload"/>  
<br/>
FeedBack    File:<html:file property="theFile" />  
<html:submit value="upload" onclick="this.form.action='uploadAction.do?method=upFBFile'"/>  
</html:form>


这是后台action过程

Select一行的submit
public ActionForward upFile(ActionMapping mapping, ActionForm form,
HttpServletRequest request, HttpServletResponse response)
throws Exception {
String filePathName = "";
if (form instanceof UploadForm) {
String encoding = request.getCharacterEncoding();

if ((encoding != null) && (encoding.equalsIgnoreCase("utf-8"))) {
response.setContentType("text/html; charset=gb2312");
}
UploadForm theForm = (UploadForm) form;
FormFile file = theForm.getTheFile();
String contentType = file.getContentType();
String zoneName = theForm.getName();
String size = (file.getFileSize() + " bytes");
String fileName = file.getFileName();
//
System.out.println("fileName="+fileName); //这里打印为"fileName=",明显没有值
String timeStr = df.getTime("yyyyMMddhhmmss");
try {
InputStream stream = file.getInputStream();
String filePath = request.getRealPath("/");
ByteArrayOutputStream baos = new ByteArrayOutputStream();
OutputStream bos = null;
filePathName = filePath+ "files" + "\\"+ timeStr+file.getFileName();
String pathName = request.getSession().getServletContext().getRealPath("/") + "files";
File files= new File(pathName);
if(files.exists()&&files.isDirectory()){
bos = new FileOutputStream(filePath + "files"+ "\\"
+ timeStr+file.getFileName());
int bytesRead = 0;
byte[] buffer = new byte[8192];
while ((bytesRead = stream.read(buffer, 0, 8192)) != -1) {
bos.write(buffer, 0, bytesRead);
}
}else{
boolean flag = files.mkdir();
if(flag){
bos = new FileOutputStream(filePath + "files"+ "\\"
+ timeStr+file.getFileName());
int bytesRead = 0;
byte[] buffer = new byte[8192];
while ((bytesRead = stream.read(buffer, 0, 8192)) != -1) {
bos.write(buffer, 0, bytesRead);
}
}
}
bos.close();
stream.close();
} catch (Exception e) {
}
request.setAttribute("contentType", contentType);
request.setAttribute("size", size);
request.setAttribute("fileName", fileName);
request.setAttribute("filePathName", filePathName);
request.setAttribute("zoneName", zoneName);
return mapping.findForward("display");
}
return null;
}


Feedback一行的submit
public ActionForward upFBFile(ActionMapping mapping, ActionForm form,
HttpServletRequest request, HttpServletResponse response)
throws Exception {
String filePathName = "";
if (form instanceof UploadForm) {
String encoding = request.getCharacterEncoding();

if ((encoding != null) && (encoding.equalsIgnoreCase("utf-8"))) {
response.setContentType("text/html; charset=gb2312");
}
UploadForm theForm = (UploadForm) form;
FormFile file = theForm.getTheFile();
String contentType = file.getContentType();
String zoneName = theForm.getName();
String size = (file.getFileSize() + " bytes");
String fileName = file.getFileName();
String timeStr = df.getTime("yyyyMMddhhmmss");
try {
InputStream stream = file.getInputStream();
String filePath = request.getRealPath("/");
ByteArrayOutputStream baos = new ByteArrayOutputStream();
OutputStream bos = null;
filePathName = filePath+ "files" + "\\"+ timeStr+file.getFileName();
String pathName = request.getSession().getServletContext().getRealPath("/") + "files";
File files= new File(pathName);
if(files.exists()&&files.isDirectory()){
bos = new FileOutputStream(filePath + "files"+ "\\"
+ timeStr+file.getFileName());
int bytesRead = 0;
byte[] buffer = new byte[8192];
while ((bytesRead = stream.read(buffer, 0, 8192)) != -1) {
bos.write(buffer, 0, bytesRead);
}
}else{
boolean flag = files.mkdir();
if(flag){
bos = new FileOutputStream(filePath + "files"+ "\\"
+ timeStr+file.getFileName());
int bytesRead = 0;
byte[] buffer = new byte[8192];
while ((bytesRead = stream.read(buffer, 0, 8192)) != -1) {
bos.write(buffer, 0, bytesRead);
}
}
}
bos.close();
stream.close();
} catch (Exception e) {
}
request.setAttribute("contentType", contentType);
request.setAttribute("size", size);
request.setAttribute("fileName", fileName);
request.setAttribute("filePathName", filePathName);
request.setAttribute("zoneName", zoneName);
return mapping.findForward("displayFB");
}
return null;
}


这俩代码几乎似乎一样的,为什么会导致这样呢!
...全文
332 6 打赏 收藏 转发到动态 举报
写回复
用AI写文章
6 条回复
切换为时间正序
请发表友善的回复…
发表回复
苦苦的潜行者 2011-09-21
  • 打赏
  • 举报
回复
结贴:
4楼问题尚未解决,最近在看struts及struts标签,希望能从中获益,暂时共用一个file,希望以后问题解决再来分享答案.
苦苦的潜行者 2011-09-15
  • 打赏
  • 举报
回复
[Quote=引用 2 楼 softroad 的回复:]
Select Excel File:<html:file property="theFile" />
FeedBack File:<html:file property="theFile" />

楼主这么有2个submit
[/Quote]

应该怎么修改呢?
苦苦的潜行者 2011-09-14
  • 打赏
  • 举报
回复
[Quote=引用 1 楼 softroad 的回复:]
property="theFile" 两个名字 一样了。
[/Quote]

我现在突然发现一种现象
就是我Select行的file没用!!
事实上这两个submit共用第二行的file
......
好惨!怎么办!
如果实在没有好的办法我只有共用file了
安心逍遥 2011-09-14
  • 打赏
  • 举报
回复
页面上要设置一下

好像也不能用request获得

具体的忘了。楼主搜一下吧

祝你好运
softroad 2011-09-14
  • 打赏
  • 举报
回复
Select Excel File:<html:file property="theFile" />
FeedBack File:<html:file property="theFile" />

楼主这么有2个submit
softroad 2011-09-14
  • 打赏
  • 举报
回复
property="theFile" 两个名字 一样了。
form表单的多文件上传,具体内容如下 formData对象可以使用一系列的键值对来模拟一个完整的表单,然后使用Ajax来发送这个表单 使用<form>表单初始化FormData对象的方式上传文件 <!--文件上传--> <form id=uploadForm enctype=multipart/form-data>
第1个上传组件commons-fileupload =============commons-fileupload ================ common-fileupload组件是apache的一个开源项目之一,可以从http://jakarta.apache.org/commons/fileupload/下载。该组件简单易用,可实现一次上传一个多个文件,并可限制文件大小。 -下载后解压zip包,将commons-fileupload-1.1.1.jar,和commons-io-1.2.jar(这里我们用的是更新的版本,但是用法是一样的)复制到tomcat的webapps\你的webapp\WEB-INF\lib\下,如果目录不存在请自建目录。 新建一个servlet: FileUpload.java用于文件上传: package com.drp.util.servlet; import java.io.IOException; import java.io.PrintWriter; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.apache.commons.fileupload.*; import java.util.*; import java.util.regex.*; import java.io.*; import org.apache.commons.fileupload.servlet.*; import org.apache.commons.fileupload.disk.DiskFileItemFactory; public class FileUpload extends HttpServlet { private String uploadPath = ""; // 用于存放上传文件的目录 private File tempPath = new File("D:\\Tomcat 5.5\\webapps\\drp1.2\\tempimages\\"); // 用于存放临时文件的目录 public void doPost(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException { res.setContentType("text/html; charset=GB18030"); PrintWriter out = res.getWriter(); System.out.println(req.getContentLength()); System.out.println(req.getContentType()); DiskFileItemFactory factory = new DiskFileItemFactory(); // maximum size that will be stored in memory //允许设置内存存储数据的门限,单位:字节 factory.setSizeThreshold(4096); // the location for saving data that is larger than getSizeThreshold() //如果文件大小大于SizeThreshold,则保存到临时目录 factory.setRepository(new File("D:\\Tomcat 5.5\\webapps\\drp1.2\\tempimages")); ServletFileUpload upload = new ServletFileUpload(factory); // maximum size before a FileUploadException will be thrown //最大上传文件,单位:字节 upload.setSizeMax(1000000); try { List fileItems = upload.parseRequest(req); // assume we know there are two files. The first file is a small //
<script src="http://csdnimg.cn/pubnav/js/pub_topnav_2011.js"type="text/javascript">
<script type="text/javascript">BAIDU_CLB_fillSlot("198363");
<script type="text/javascript">BAIDU_CLB_fillSlot("198364");
下载频道>资源上传
<form id="uploadform" name="uploadform" action="/upload/do_upload" enctype="multipart/form-data" method="POST" onsubmit="return false;">
 
  • (未选择文件)
  • 您可以上传小于50MB的文件
资源名称:
  不小于5个汉字或10个字母,详细的标题容易被下载。
资源类型:
关键词(Tag):
  多个关键字请用空格分隔,最多填写5个。点击右侧我的Tag可快速添加
所属分类:  
资源分:
资源描述:
 
  • 描述>=20个字符,不支持HTML标签。
  • 详细的资源描述有机会获得我们的推荐,更有利于他人下载,赚取更多积分。
验证码:
 
上传须知
* 如涉及侵权内容,您的资源将被移除
* 请勿上传小说、mp3、图片等与技术无关的内容.一旦发现将被删除
* 请勿在未经授权的情况下上传任何涉及著作权侵权的资源,除非该资源完全由您个人创作
* 点击上传资源即表示您确认该资源不违反资源分享的使用条款,并且您拥有该资源的所有版权或者上传资源的授权
form>
<script type="text/javascript" src="/js/jquery.selectsort.js"> function getStrLength(str) { var len = 0; for (var i=0; i= 0x0001 && c <= 0x007e) || (0xff60<=c && c<=0xff9f)) { len++; }else { len+=2; } } return len; } function stopupload() { if(navigator.appName == "Microsoft Internet Explorer") window.document.execCommand('Stop'); else window.stop(); } var xhr; $(document).ready(function() { $('#btn_submit').click(function(){ if(validate()) { $.getJSON("/index.php/upload/checkform/"+ $("#txt_validcode").serialize(), function(data){ if(data.succ==0) { alert(data.errmsg); $("#imgValidcode").attr('src','/index.php/rest/tools/validcode/uploadvalidcode/'+Math.random()); }else{ xhr = $('#uploadform').ajaxSubmit({ dataType: 'json', beforeSubmit: function(a,f,o) { startProgress(); }, success: function(data) { $("#txt_title").val(''); $("#txt_tag").val(''); $("#txt_desc").val(''); $("#txt_userfile").val(''); $('#li_userfile').html('未选择文件'); $("#sel_filetype").empty(); $("#sel_primary").empty(); $("#sel_subclass").empty(); $("#sel_score").empty(); $("#txt_validcode").val(''); $("#imgValidcode").click(); stopProgress(); if(data.succ==1) { window.location.href='/upload/success'; } else { alert(data.errmsg); window.location.reload(); } } }); } }); } return false; }); $("#imgValidcode").click(function(){ $("#imgValidcode").attr("src","/index.php/rest/tools/validcode/uploadvalidcode/1"+Math.random()); }); $('#sel_primary').selectsort('#sel_primary','#sel_subclass',''); }); function show_uploadfile() { var filename = $('#txt_userfile').val(); filename = filename.replace(/C:\\fakepath\\/, ''); $('#li_userfile').html('( '+filename+' )'); } function addtag(tag) { var tags = $("#txt_tag").val(); var arrtags=tags.split(" "); var dtags = new Array; var j=0; for(var i=0;i4) { alert('最多允许填写5个Tag!'); return ; } tags = tags + " "+tag; $("#txt_tag").val(tags); } function validate() { if(jQuery.trim($("#txt_userfile").val())=='') { alert('请选择上传的文件!'); $("#txt_userfile").focus(); return false; } if(jQuery.trim($("#txt_title").val())=='') { alert('请填写资源的标题!'); $("#txt_title").focus(); return false; } if(jQuery.trim($("#txt_title").val()).length>80) { alert('您的标题太长了!'); $("#txt_title").focus(); return false; } if(getStrLength(jQuery.trim($("#txt_title").val()))<10) { alert('标题写的详细更容易被他人下载!'); $("#txt_title").focus(); return false; } if($("#sel_filetype").val()<1) { alert('请选择资源类型!'); $("#sel_filetype").focus(); return false; } if(jQuery.trim($("#txt_tag").val())=='') { alert('请填写资源的Tag!'); $("#txt_tag").focus(); return false; } if(jQuery.trim($("#txt_tag").val()).length<2) { alert('资源Tag需要大于2个字符!'); $("#txt_tag").focus(); return false; } if(jQuery.trim($("#txt_tag").val()).split(" ").length>5) { alert('最多允许填写5个Tag!'); $("#txt_tag").focus(); return false; } if($("#sel_subclass").val()<1000) { alert('请选择分类!'); $("#sel_primary").focus(); return false; } if(jQuery.trim($("#txt_desc").val())=='') { alert('请填写资源描述!'); $("#txt_desc").focus(); return false; } if(jQuery.trim($("#txt_desc").val()).length<20) { alert('资源描述可以把电子书的概述、源代码的说明、文档的片段填在这里,描述详细会获得我们的推荐,更容易被他人下载!描述大于20字不是问题吧!'); $("#txt_desc").focus(); return false; } if($("#cb_agree").attr("checked")==false) { alert('请先同意CSDN资源上传协议!'); $("#cb_agree").focus(); return false; } if(jQuery.trim($("#txt_validcode").val())=='') { alert('请输入验证码!'); $("#txt_validcode").focus(); return false; } return true; } function stopProgress() { $(document).progressDialog.hideDialog("#pop_add_org"); } function startProgress(){ $(document).progressDialog.showDialog("#pop_add_org"); $("#pop_add_org").fadeTo("slow",0.8); setTimeout("getProgress()", 500); } function getProgress(){ $.getJSON("/index.php/upload/get_progress/2d7901bf58ca1838163de4247b0bc5a2", function(data){ if(data.succ<0){ alert(data.errmsg); window.location.reload(); } if (data.done==0 && data.succ>0){ $("#uploadprogressbar").html(data.percent+"%"); $("#uploadprogressbarimg").html(''); $("#uploadrate").html(data.rate_hum); $("#uploadelapsetime").html(data.elapsetime); $("#uploadlefttime").html(data.lefttime); $("#uploadtotal").html(data.total_hum); $("#uploadcurrent").html(data.current_hum); setTimeout("getProgress()", 500); } }); } <script type="text/javascript">document.write(""); <script type="text/javascript" src="http://www.csdn.net/ui/scripts/Csdn/counter.js">
<script type="text/javascript"> function setTab(m,n){ var tli=document.getElementById("menu"+m).getElementsByTagName("a"); var mli=document.getElementById("main"+m).getElementsByTagName("ul"); for(i=0;iform){ var key=$.trim(thisform.q.value); if(key==""){ alert("关键字不能为空!"); } else{ key=key.replace(/\+/g,"%2B").replace(/\//g,"%2F"); var url="/search?q="+key; window.location.href=url; } return false; } <script src="http://csdnimg.cn/pubnav/js/pub_topnav_2011.js"type="text/javascript">
<script type="text/javascript">BAIDU_CLB_fillSlot("198363");
<script type="text/javascript">BAIDU_CLB_fillSlot("198364");
下载频道>资源上传
<form id="uploadform" name="uploadform" action="/upload/do_upload" enctype="multipart/form-data" method="POST" onsubmit="return false;">
 
  • (未选择文件)
  • 您可以上传小于50MB的文件
资源名称:
  不小于5个汉字或10个字母,详细的标题容易被下载。
资源类型:
关键词(Tag):
  多个关键字请用空格分隔,最多填写5个。点击右侧我的Tag可快速添加
所属分类:  
资源分:
资源描述:
 
  • 描述>=20个字符,不支持HTML标签。
  • 详细的资源描述有机会获得我们的推荐,更有利于他人下载,赚取更多积分。
验证码:
 
上传须知
* 如涉及侵权内容,您的资源将被移除
* 请勿上传小说、mp3、图片等与技术无关的内容.一旦发现将被删除
* 请勿在未经授权的情况下上传任何涉及著作权侵权的资源,除非该资源完全由您个人创作
* 点击上传资源即表示您确认该资源不违反资源分享的使用条款,并且您拥有该资源的所有版权或者上传资源的授权
form>
<script type="text/javascript" src="/js/jquery.selectsort.js"> function getStrLength(str) { var len = 0; for (var i=0; i= 0x0001 && c <= 0x007e) || (0xff60<=c && c<=0xff9f)) { len++; }else { len+=2; } } return len; } function stopupload() { if(navigator.appName == "Microsoft Internet Explorer") window.document.execCommand('Stop'); else window.stop(); } var xhr; $(document).ready(function() { $('#btn_submit').click(function(){ if(validate()) { $.getJSON("/index.php/upload/checkform/"+ $("#txt_validcode").serialize(), function(data){ if(data.succ==0) { alert(data.errmsg); $("#imgValidcode").attr('src','/index.php/rest/tools/validcode/uploadvalidcode/'+Math.random()); }else{ xhr = $('#uploadform').ajaxSubmit({ dataType: 'json', beforeSubmit: function(a,f,o) { startProgress(); }, success: function(data) { $("#txt_title").val(''); $("#txt_tag").val(''); $("#txt_desc").val(''); $("#txt_userfile").val(''); $('#li_userfile').html('未选择文件'); $("#sel_filetype").empty(); $("#sel_primary").empty(); $("#sel_subclass").empty(); $("#sel_score").empty(); $("#txt_validcode").val(''); $("#imgValidcode").click(); stopProgress(); if(data.succ==1) { window.location.href='/upload/success'; } else { alert(data.errmsg); window.location.reload(); } } }); } }); } return false; }); $("#imgValidcode").click(function(){ $("#imgValidcode").attr("src","/index.php/rest/tools/validcode/uploadvalidcode/1"+Math.random()); }); $('#sel_primary').selectsort('#sel_primary','#sel_subclass',''); }); function show_uploadfile() { var filename = $('#txt_userfile').val(); filename = filename.replace(/C:\\fakepath\\/, ''); $('#li_userfile').html('( '+filename+' )'); } function addtag(tag) { var tags = $("#txt_tag").val(); var arrtags=tags.split(" "); var dtags = new Array; var j=0; for(var i=0;i4) { alert('最多允许填写5个Tag!'); return ; } tags = tags + " "+tag; $("#txt_tag").val(tags); } function validate() { if(jQuery.trim($("#txt_userfile").val())=='') { alert('请选择上传的文件!'); $("#txt_userfile").focus(); return false; } if(jQuery.trim($("#txt_title").val())=='') { alert('请填写资源的标题!'); $("#txt_title").focus(); return false; } if(jQuery.trim($("#txt_title").val()).length>80) { alert('您的标题太长了!'); $("#txt_title").focus(); return false; } if(getStrLength(jQuery.trim($("#txt_title").val()))<10) { alert('标题写的详细更容易被他人下载!'); $("#txt_title").focus(); return false; } if($("#sel_filetype").val()<1) { alert('请选择资源类型!'); $("#sel_filetype").focus(); return false; } if(jQuery.trim($("#txt_tag").val())=='') { alert('请填写资源的Tag!'); $("#txt_tag").focus(); return false; } if(jQuery.trim($("#txt_tag").val()).length<2) { alert('资源Tag需要大于2个字符!'); $("#txt_tag").focus(); return false; } if(jQuery.trim($("#txt_tag").val()).split(" ").length>5) { alert('最多允许填写5个Tag!'); $("#txt_tag").focus(); return false; } if($("#sel_subclass").val()<1000) { alert('请选择分类!'); $("#sel_primary").focus(); return false; } if(jQuery.trim($("#txt_desc").val())=='') { alert('请填写资源描述!'); $("#txt_desc").focus(); return false; } if(jQuery.trim($("#txt_desc").val()).length<20) { alert('资源描述可以把电子书的概述、源代码的说明、文档的片段填在这里,描述详细会获得我们的推荐,更容易被他人下载!描述大于20字不是问题吧!'); $("#txt_desc").focus(); return false; } if($("#cb_agree").attr("checked")==false) { alert('请先同意CSDN资源上传协议!'); $("#cb_agree").focus(); return false; } if(jQuery.trim($("#txt_validcode").val())=='') { alert('请输入验证码!'); $("#txt_validcode").focus(); return false; } return true; } function stopProgress() { $(document).progressDialog.hideDialog("#pop_add_org"); } function startProgress(){ $(document).progressDialog.showDialog("#pop_add_org"); $("#pop_add_org").fadeTo("slow",0.8); setTimeout("getProgress()", 500); } function getProgress(){ $.getJSON("/index.php/upload/get_progress/2d7901bf58ca1838163de4247b0bc5a2", function(data){ if(data.succ<0){ alert(data.errmsg); window.location.reload(); } if (data.done==0 && data.succ>0){ $("#uploadprogressbar").html(data.percent+"%"); $("#uploadprogressbarimg").html(''); $("#uploadrate").html(data.rate_hum); $("#uploadelapsetime").html(data.elapsetime); $("#uploadlefttime").html(data.lefttime); $("#uploadtotal").html(data.total_hum); $("#uploadcurrent").html(data.current_hum); setTimeout("getProgress()", 500); } }); } <script type="text/javascript">document.write(""); <script type="text/javascript" src="http://www.csdn.net/ui/scripts/Csdn/counter.js">
<script type="text/javascript"> function setTab(m,n){ var tli=document.getElementById("menu"+m).getElementsByTagName("a"); var mli=document.getElementById("main"+m).getElementsByTagName("ul"); for(i=0;iform){ var key=$.trim(thisform.q.value); if(key==""){ alert("关键字不能为空!"); } else{ key=key.replace(/\+/g,"%2B").replace(/\//g,"%2F"); var url="/search?q="+key; window.location.href=url; } return false; }

67,513

社区成员

发帖
与我相关
我的任务
社区描述
J2EE只是Java企业应用。我们需要一个跨J2SE/WEB/EJB的微容器,保护我们的业务核心组件(中间件),以延续它的生命力,而不是依赖J2SE/J2EE版本。
社区管理员
  • Java EE
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧