这块本来已经做好了,在本机上测试也无误,只是每次打开对话框的时候有点慢,可能是因为在action里用JFileChooser打开的
没想到部署到服务器以后,对话框一点就卡住了,有时候等半天对话框都不出来然后服务器就崩溃了,当时我也崩溃了。
原来的代码:
jsp部分
<a href="studentAction.do?action=toImportStudentInfo"> <img src="image/botton/import.jpg" width="102" height="29" border="0"/> </a>
Action部分
JFileChooser jfc = new JFileChooser (); //打开文件浏览对话框 jfc.setAcceptAllFileFilterUsed(true); //去掉显示所有文件这个过滤器。 jfc.setFileFilter(new ExcelFileFilter("xls")); //添加excel文件的过滤器 int result=jfc.showOpenDialog(null); if (result == JFileChooser.APPROVE_OPTION) { try{ File fSource=jfc.getSelectedFile(); FileInputStream in=new FileInputStream(fSource); HSSFWorkbook workbook= new HSSFWorkbook(in); …… }catch(Exception e){ e.printStackTrace(); return null; } }
具体关于POI HSSF的代码另外写(因为在实现的时候也遇到过一个纠结了很久的问题),对话框出来是java风格(其丑无比),于是又加在JFileChooser前加一段代码将其改成伪windows风格
try { //打开文件窗口设置为windows风格 UIManager.setLookAndFeel( UIManager.getSystemLookAndFeelClassName()); } catch (Exception e) { e.printStackTrace(); }
以上代码在本机上运行都是没问题的,问题是部署到服务器上,再访问就抽风了!!
修改后的代码:
jsp部分:
<form id="form2" > <input id="filename" type="file" name="filename" class="textarea"> <a id="a1" href="javascript:void(0)" onclick="submitFile()" > <img src="image/botton/import.jpg" width="102" height="29" border="0"/> </a> </form>
JS部分:
<script type="text/javascript"> function submitFile(){ var a = document.getElementById('filename').value; var url="studentAction.do?action=toImportStudentInfo&file="+encodeURI(encodeURI(a)); window.location =url; } </script>
我尝试在后台直接用request.getParament("filename")来获得这个路径,但是一直传null,原因不明,于是只能通过拐弯抹角的办法从前台传参。
其中encodeURI()是为了转码,不然路径里带中文字,传到后台就是乱码。
Action部分:
String s1=request.getParameter("file")+""; s1=java.net.URLDecoder.decode(s1, "UTF-8"); if (s1!=null) { try{ File fSource = new File(s1); String fileName=fSource.getAbsolutePath(); FileInputStream in=new FileInputStream(fSource); HSSFWorkbook workbook= new HSSFWorkbook(in); …… }catch(Exception e){ e.printStackTrace(); return null; } }
(1)为什么用JS而不用正常的表单提交来从后台获得?
因为要重写提交方法以后,后台怎么都获得不了filename永远是null,解决无能之后改成这种方式
(2)因为安全问题,许多浏览器会把获得的路径替换成fakepath,比如chrome,FF,IE如果设置安全级别高也会发生这种情况,也就是代码中前台的a和后台的s1(文件本地路径),肿么办?
尚未解决,解决了再接着写TAT