标签:
环境:Servlet2.5
第三方的上传组件:
commons-fileupload
依赖包:
connons-io
页面
1、form表单需要增加:enctype="multipart/form-data" 以字节流形式
2、form表单里面增加上传组件:input="file"
3、取消上传:<button onclick="javascript:window.opener == null;window.close();">取消上传</button>
<form id="form1" method="post" action="Upload" enctype="multipart/form-data"> <table> <tr> <td width="25%" align="right">上传文件:</td> <td><input id="file1" type="file" NAME="file1" style="width: 300px;"></td> </tr> <tr align="center" valign="middle"> <td height="60" colspan="2"> <input type="submit" id="BtnOK" value="确认上传"> <button onclick="javascript:window.opener == null;window.close();">取消上传</button> </td> </tr> <tr align="center" valign="middle"> <td height="60" colspan="2"><input type="text" name="possess" value="非提交控件的值"></td> </tr> </table> </form>
代码:
新增类 MutiFileUpload.java 对fileupload组件进行简单封装 , Struts2中还可以接着用。
import java.io.UnsupportedEncodingException; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; import javax.servlet.http.HttpServletRequest; import org.apache.commons.fileupload.FileItem; import org.apache.commons.fileupload.FileUploadException; import org.apache.commons.fileupload.disk.DiskFileItemFactory; import org.apache.commons.fileupload.servlet.ServletFileUpload; /** * 编码问题(setHeaderEncoding),这个方法是从FileUploadBase类里继承的, * 根据其说明,当读取上传表单的各部分时会用到该encoding,如果没有指定 * encoding * 则使用系统缺省的encoding。建议在这里设置成utf-8,并把jsp * 的charset也设置成utf-8,否则可能会出现乱码。 * */ @SuppressWarnings("unchecked") public class MutiFileUpload{ public Map<String,String> parameters ; //保存普通form表单域 public Map<String,FileItem> files; //保存上传的文件
//将文件保存在内存还是磁盘临时文件夹的默认临界值,值为10240,即10kb private int sizeThreshold = DiskFileItemFactory.DEFAULT_SIZE_THRESHOLD; private long sizeMax = 1024 * 1024 * 20 ; //上传文件的大小限制; private String encoding = "UTF-8"; //字符编码,当读取上传表单的各部分时会用到该encoding public String getEncoding() { return encoding; } public void setEncoding(String encoding) { this.encoding = encoding; } public long getSizeMax() { return sizeMax; } public void setSizeMax(long sizeMax) { this.sizeMax = sizeMax; } public int getSizeThreshold() { return sizeThreshold; } public void setSizeThreshold(int sizeThreshold) { this.sizeThreshold = sizeThreshold; } public void parse(HttpServletRequest request){ parameters = new HashMap<String,String>(); files = new HashMap<String,FileItem>(); DiskFileItemFactory factory = new DiskFileItemFactory(); //设置临界值约束 factory.setSizeThreshold(sizeThreshold); ServletFileUpload upload = new ServletFileUpload(factory); upload.setSizeMax(sizeMax); upload.setHeaderEncoding(encoding); try { List items = upload.parseRequest(request); Iterator iterator = items.iterator(); while(iterator.hasNext()){ FileItem item = (FileItem)iterator.next(); if(item.isFormField()){ String fieldName = item.getFieldName(); String value = new String(item.getString(encoding)); parameters.put(fieldName, value); }else{ String fieldName = item.getFieldName(); files.put(fieldName, item); } } } catch (FileUploadException e) { e.printStackTrace(); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } } /** 得到上传文件的文件名 * @param item * @return */ public String getFileName(FileItem item){ String fileName = item.getName(); fileName = replace(fileName,"\\","/"); fileName = fileName.substring(fileName.lastIndexOf("/")+1); return fileName; } /**字符串替换 * @param source * @param oldString * @param newString * @return */ public static String replace(String source, String oldString, String newString) { StringBuffer output = new StringBuffer(); int lengthOfSource = source.length(); int lengthOfOld = oldString.length(); int posStart = 0; int pos; while ((pos = source.indexOf(oldString, posStart)) >= 0) { output.append(source.substring(posStart, pos)); output.append(newString); posStart = pos + lengthOfOld; } if (posStart < lengthOfSource) { output.append(source.substring(posStart)); } return output.toString(); } }
建立上传用Servlet,doGet方法请求doPost。在doPost方法中编写如下代码:
public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { MutiFileUpload fileUpload = new MutiFileUpload();
//解析请求,分解form表单的元素 fileUpload.parse(request); //测试非上传组件的数据是否可以获取 System.out.println( fileUpload.parameters.get("possess") ); Iterator iterator = fileUpload.files.values().iterator(); while(iterator.hasNext()){ FileItem item = (FileItem) iterator.next(); String fileName = fileUpload.getFileName(item); //获取上传文件路径 String serverPath = request.getSession().getServletContext().getRealPath("");
//创建上传的文件 File file = new File( serverPath+"/upload/"+fileName); try { if( !file.isDirectory()){
//上传文件 item.write(file); } } catch (Exception e) { e.printStackTrace(); } } }
文件上传:commons-fileupload + Servlet 2.5
标签:
原文地址:http://www.cnblogs.com/morlin/p/4891894.html