我们的java上传文件,需要form同步上传,并且需要设置enctype为multipart/form-data。
如果将form使用ajax异步提交的话,将会报错说enctype不是multipart/form-data类型
但有时候确实又有酱紫的需求,可以实现,需要借助jquery.form.js 插件
插件下载地址为:
http://yun.baidu.com/share/link?shareid=1698628055&uk=2836507213
下面贴出关键性代码
jsp代码为:
<form id= "uploadForm"> <p >指定文件名: <input type="text" name="filename" value= ""/></p > <p >上传文件: <input type="file" name="file"/></p> <input type="button" value="上传" onclick="doUpload()" /> </form> <script> function doUpload(){ var formData = new FormData($( "#uploadForm" )[0]); $.ajax({ url: ‘${pageContext.request.contextPath}/UploadHandleServlet‘ , type: ‘POST‘, data: formData, async: false, cache: false, contentType: false, processData: false, success: function (returndata) { alert(returndata); }, error: function (returndata) { alert(returndata); } }); } </script>
后台代码不变,和普通form上传代码一样
SimpleDateFormat sdf1 = new SimpleDateFormat("yyyyMMddHHmmss"); String savePath =request.getSession().getServletContext().getRealPath("/WEB-INF/upload"); File file = new File(savePath); if (!file.exists()) { file.mkdir(); } String message =""; try{ DiskFileItemFactory factory = new DiskFileItemFactory(); factory.setSizeThreshold(1024*100); factory.setRepository(file); ServletFileUpload upload = new ServletFileUpload(factory); upload.setHeaderEncoding("UTF-8"); List<FileItem> list = upload.parseRequest(request); //正则匹配,过滤路径取文件名 String regExp = ".+\\\\(.+)$"; Pattern p = Pattern.compile(regExp); String fileName=""; for(FileItem item : list){ if(item.isFormField()){ String name = item.getFieldName(); String value = item.getString("UTF-8"); System.out.println(name + "=" + value); }else{ String name = item.getName(); name = name.substring(name.lastIndexOf("\\")+1); fileName = savePath+"/"+ sdf1.format(new Date()) + "_"+name; item.write(new File(fileName)); } } message = "文件上传成功!"; }catch (Exception e) { message= "文件上传失败!"; e.printStackTrace(); }
亲测有用
本文出自 “bulajunjun” 博客,请务必保留此出处http://5148737.blog.51cto.com/5138737/1774543
原文地址:http://5148737.blog.51cto.com/5138737/1774543