文件上传之文件读写

来源:互联网 发布:外文期刊数据库检索 编辑:程序博客网 时间:2024/06/05 07:08


实例(controller):
      @RequestMapping("/NoaddEmp")               public String NOaddEmp(@RequestParam("file") CommonsMultipartFile file,                         Employe employe,HttpServletRequest request) {        Long begin = System.currentTimeMillis();      //getRealPath("/img/photo/") .../img/photo 对你没看错 不是.../img/photo/     String fileUrl = request.getRealPath("/img/photo/")            +File.separator+file.getOriginalFilename();         FileOutputStream os=null;       InputStream is =null;try {      os = new FileOutputStream(fileUrl);      //is = new FileInputStream(file);     is = file.getInputStream();     /*  byte[] buffer =new byte[1024];      int len =0;      while((len=is.read(buffer))!=-1){  //读取写入文件 方法1      os.write(buffer,0,len);      }      */       int len=0;       while((len=is.read())!=-1){ //读取写入文件 方法2       os.write(len);     }      os.flush();      is.close();      os.close();       } catch (FileNotFoundException e) {         e.printStackTrace();       } catch (IOException e) {         e.printStackTrace();       }    Long end = System.currentTimeMillis();    System.out.println("耗时"+(end-begin)+"ms");     employe.setPhoto("/img/photo/"+file.getOriginalFilename());    boolean bl = empService.save(employe);    return"redirect:/emp/toList";  }


0 0
原创粉丝点击