因为浏览器之间有差异,考虑到兼容性,选择在后台进行文件的格式判断,文件大小约束,比较好的一个方案前台代码
function ajaxFileUpload(){ alert("hi"); var filepath = $("input[<span style="background-color: rgb(51,51,255);">name</span>='file']").val(); var extStart = filepath.lastIndexOf("."); var ext = filepath.substring(extStart,filepath.length).toUpperCase(); $.ajaxFileUpload( { url:'<%=request.getContextPath() %>/inSer/scwtUpload',//需要链接到服务器地址 secureuri:false,file<span style="background-color: rgb(51,255);">ElementId</span>:'file',//文件选择框的id属性 dataType: 'json',//服务器返回的格式,可以是json success: function (data,status) //相当于java中try语句块的用法 { alert(data.responseText); },error: function (data,status,e) //相当于java中catch语句块的用法 { alert(data.responseText); } } ); }后台代码:
@RequestMapping(value="/scwtUpload",method=RequestMethod.POST) @ResponseBody public void scwtUpload(@RequestParam("file") CommonsMultipartFile file,HttpServletRequest request,HttpServletResponse response) throws IOException,JSONException{ String result = "上传成功"; boolean flag = true ; long size = file.getSize(); String fieldName = file.getFileItem().getName(); int index = fieldName.indexOf("."); String extension = fieldName.substring(index+1).toUpperCase(); if(!extension.equals("DOC")){ result = "只允许上传DOC格式文件"; flag = false; } if(size>10485760){ result = "文件大小超过10M,请重新上传文件"; flag = false; } FileOutputStream os = null; InputStream in = null; if(flag){ try{ Date date = new Date(); SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); String time = sdf.format(date).replaceAll("-","").replaceAll(":","").replaceAll(" ",""); String path = request.getSession().getServletContext().getRealPath("/")+time+file.getOriginalFilename(); os = new FileOutputStream(path); in = file.getInputStream(); int b=0; while((b=in.read())!=-1){ os.write(b); } os.flush(); }finally{ os.close(); in.close(); } } response.setContentType("text/html;charset=UTF-8"); response.getWriter().write(result); }原文链接:https://www.f2er.com/ajax/163069.html