1、用 file标签实现,加上multiple属性可以多选,但是IE浏览器不支持该属性
页面代码:
<form action="uploadfile.action" method="post" enctype="multipart/form-data"> <table> <tr> <td><input type="file" id ="file" name="file" multiple="multiple" size="40"></td> </tr> <tr> <td colspan="2" align="center"><input type="submit" value="上传"/></td> </tr> </table></form>
后台处理:
items = upload.parseRequest(request);返回空值,解决方法分为3步
1)、增加一个类
public class MyRequestParser extends JakartaMultiPartRequest {public void parse(HttpServletRequest servletRequest, String saveDir) throws IOException {} }
2)、修改struts.xml
<struts> <!-- struts2.3.4版本 --><!-- <bean type= "org.apache.struts2.dispatcher.multipart.MultiPartRequest" name= "myRequestParser" class= "actiontest.MyRequestParser" scope= "default" optional= "true " /> <constant name= "struts.multipart.handler" value= "myRequestParser" /> --> <!-- struts2.3.15.1 以后的版本 --> <bean type="org.apache.struts2.dispatcher.multipart.MultiPartRequest" name="myMultiPartRequest" class="actiontest.MyRequestParser" scope="default" optional="true"/> <constant name="struts.multipart.parser" value="myMultiPartRequest" />
3、
public String uploadFiles() throws IOException { request.setCharacterEncoding("UTF-8"); PRintWriter out = null; FileItemFactory factory = new DiskFileItemFactory(); ServletFileUpload upload = new ServletFileUpload(factory); File directory = null; List<FileItem> items = new ArrayList(); try {
//该句代码在执行时返回的items为空 items = upload.parseRequest(request); // 得到所有的文件 Iterator<FileItem> it = items.iterator(); while (it.hasNext()) { FileItem fItem = (FileItem) it.next(); String fName = ""; Object fValue = null; if (fItem.isFormField()) { // 普通文本框的值 fName = fItem.getFieldName(); fValue = fItem.getString("UTF-8"); } else { // 获取上传文件的值 fName = fItem.getFieldName(); fValue = fItem.getInputStream(); String name = fItem.getName(); if(name != null && !("".equals(name))) { name = name.substring(name.lastIndexOf(File.separator) + 1); directory = new File("d://test"); directory.mkdirs(); String filePath = ("d://test")+ File.separator + name; InputStream is = fItem.getInputStream(); FileOutputStream fos = new FileOutputStream(filePath); byte[] buffer = new byte[1024]; while (is.read(buffer) > 0) { fos.write(buffer, 0, buffer.length); } fos.flush(); fos.close(); } } } } catch (Exception e) { return "error"; } return "success"; }
新闻热点
疑难解答