smartupload实现文件上传时获取表单数据(推荐)
实现文件上传的form表单必须满足两个条件:method="post"enctype="multipart/form-data"
表单中enctype="multipart/form-data"的意思是设置表单的MIME编码。默认情况,这个编码格式是application/x-www-form-urlencoded,不能用于文件上传;只有使用了multipart/form-data,才能完整的传递文件数据。enctype="multipart/form-data"是上传二进制数据;form里面的input的值以二进制的方式传过去。所以request就得不到值了,也就是说加了这段代码,用request就会传递不成功。
取表单字段值时,用下面的方式:
SmartUploadsu=newSmartUpload();//新建一个SmartUpload对象 su.getRequest().getParameterValues(Stringname);//取数组值 su.getRequest().getParameter(Stringname);//取单个参数单个值
注:在使用SmartUpload时需要添加相应的jar包
Stringsoftname=su.getRequest().getParameter("softname");
注意:一定要在su.upload();,之后使用,才可以获得值!!
<spanstyle="font-size:14px;">publicvoiddoPost(HttpServletRequestrequest,HttpServletResponseresponse) throwsServletException,IOException{ SmartUploadmySmartUpload=newSmartUpload(); try{ //Initialization mySmartUpload.initialize(config,request,response); mySmartUpload.setMaxFileSize(10*1024*1024);//限制上传文件的大小 //mySmartUpload.setAllowedFilesList("txt,html,jpg,js");//设置允许上传的文件类型 mySmartUpload.setDeniedFilesList("exe,doc");//设置禁止上传的文件列表 mySmartUpload.upload(); StringhString=mySmartUpload.getRequest().getParameter("name1"); //System.out.println(hString); //System.out.println(mySmartUpload.getFiles().getCount()); for(inti=0;i<mySmartUpload.getFiles().getCount();i++){//多个文件的上传 Filefile=mySmartUpload.getFiles().getFile(i); if(file.getSize()!=0){ //拼凑上传文件的新名称 StringfileNameString=System.currentTimeMillis()+"."+file.getFileExt(); //通过servlet的实际路径拼凑上传文件的保存路径,实际使用需要修改此路径 Stringpath="/upload123123"+java.io.File.separator+fileNameString; file.saveAs(path); } Thread.sleep(100); /*下载文件的语句 mySmartUpload.downloadFile("/路径"+"文件名称");*/ } }catch(Exceptione){ e.printStackTrace(); } }</span>