日期:2014-05-16 浏览次数:20857 次
<form id="upForm"> 请选择文件:<input type="file" name="file1"><br /> 文件描述: <textarea cols="70" rows="5" name="desc"></textarea> <br /> <input type="button" id="btn" value="上传"> </form> <script type="text/javascript"> Ext.onReady(function() { Ext.MessageBox.alert("测试", "测试Ext是否运行"); Ext.get("btn").on("click", function() { Ext.Ajax.request({ url : "FileUpServlet", isUpload : true, form : "upForm", success : function(response) { Ext.MessageBox.alert("上传成功", response.responseText); } }); }); }); </script>
public class FileUpServlet extends HttpServlet { private static final long serialVersionUID = 1L; public FileUpServlet() { super(); } @Override public void service(ServletRequest request, ServletResponse response) throws ServletException, IOException { request.setCharacterEncoding("utf-8"); response.setCharacterEncoding("utf-8"); response.setContentType("text/html;charset=utf-8"); ServletContext ctx = this.getServletContext(); String userFilePath = ctx.getRealPath("userFile"); DiskFileItemFactory factory = new DiskFileItemFactory(); factory.setSizeThreshold(1024 * 1024); factory.setRepository(new File(userFilePath)); ServletFileUpload upload = new ServletFileUpload(factory); upload.setSizeMax(10 * 1024 * 1024); try { List<FileItem> fileItems = upload.parseRequest((HttpServletRequest) request); System.out.println(fileItems.size()); Iterator<FileItem> iter = fileItems.iterator(); while (iter.hasNext()) { FileItem fi = iter.next(); if (fi.isFormField()) { String fieldName = fi.getFieldName(); String fieldvalue = fi.getString(); System.out.println("name:" + fieldName); System.out.println("value:" + fieldvalue); } else { String filePath = fi.getName(); if (filePath != null) { System.out.println(filePath); } if (StringUtil.isBlank(filePath)) { continue; } String extensionName = filePath.substring( filePath.lastIndexOf("."), filePath.length()); // String contentType = fi.getContentType(); // boolean isInMemory = fi.isInMemory(); // long sizeInBytes = fi.getSize(); String url = userFilePath +"\\"+ StringUtil.getUUID() + extensionName; File uploadedFile = new File(url); if (!uploadedFile.exists()) { uploadedFile.getParentFile().mkdirs(); } fi.write(uploadedFile); } } PrintWriter out = response.getWriter(); out.print("创建成功"); out.flush(); out.close(); } catch (Exception e) { e.printStackTrace(); } } }