java文件上传方式1servlet 方式2springmvc
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { request.setCharacterEncoding("utf-8"); response.setCharacterEncoding("utf-8"); response.setContentType("text/html,charset=utf-8"); Boolean ismu=ServletFileUpload.isMultipartContent(request); if(ismu) { FileItemFactory ff=new DiskFileItemFactory(); ServletFileUpload sUpload=new ServletFileUpload(ff); sUpload.setFileSizeMax(1024*2);//限制上传文件大小 try { List<FileItem> gg=sUpload.parseRequest(request); Iterator<FileItem> jj=gg.iterator(); int jk=1; while(jj.hasNext()) { FileItem hh=jj.next(); if((hh.getFieldName()).equals("file")) { String filename=hh.getName(); String path=request.getSession().getServletContext().getRealPath("uploadone"); File file=new File(path,filename); hh.write(file); }else if((hh.getFieldName()).equals("name")) { jk=Integer.parseInt(hh.getString()); System.out.print(jk); } } } catch (FileUploadException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } } } 注意:将两个jar包放入项目webcontent/WEB-INF/lib中【commons-fileupload-1.3.1、commons-io-2.4】 在webcontent中新建一个存放文件的目录 。 springmvc: @RequestMapping(value="onemvc12",method=RequestMethod.POST) public String test_upload(@RequestParam("id") Integer id,@RequestParam("upload") MultipartFile mf) throws IOException { System.out.println(id); InputStream in=mf.getInputStream(); String name=mf.getOriginalFilename(); OutputStream out1=new FileOutputStream("D:\\"+name); byte[] byte1=new byte[1024]; int len=-1; while ((len=in.read(byte1)) != -1) { out1.write(byte1,0,len); } in.close(); out1.close(); return "ok"; } <!-- 实现springmvc文件上传下载 -->
<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
<property name="defaultEncoding" value="UTF-8"></property>
<property name="maxUploadSize" value="102400"></property>
</bean>