首页 > 代码库 > springMVC实现多文件上传
springMVC实现多文件上传
<h2>上传多个文件 实例</h2> <form action="/workreport/uploadMultiFile.html" method="post" enctype="multipart/form-data"> <p> 选择文件:<input type="file" name="files"> <p> 选择文件:<input type="file" name="files"> <p> 选择文件:<input type="file" name="files"> <p> <input type="submit" value="http://www.mamicode.com/提交"> </form> 复制代码 复制代码 // 多文件上传 @RequestMapping(value = "http://www.mamicode.com/uploadMultiFile") public String uploadMultiFile(HttpServletRequest request) { try { // 创建一个通用的多部分解析器 CommonsMultipartResolver multipartResolver = new CommonsMultipartResolver(request.getSession().getServletContext()); // 判断 request 是否有文件上传,即多部分请求 if (multipartResolver.isMultipart(request)) { // 转换成多部分request MultipartHttpServletRequest multiRequest = (MultipartHttpServletRequest) request; // get the parameter names of the multipart files contained in this request Iterator<String> iter = multiRequest.getFileNames(); while (iter.hasNext()) { // 取得上传文件 List<MultipartFile> multipartFiles = multiRequest.getFiles(iter.next()); String basePath = "F:/testDir/"; for (MultipartFile multipartFile : multipartFiles) { String fileName = multipartFile.getOriginalFilename(); if (StringUtils.isNotEmpty(fileName)) { multipartFile.transferTo(new File(basePath + fileName)); } } } } } catch (IllegalStateException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } return "test/success"; } 复制代码 以下是以文件流的形式保存上传的文件: 复制代码 // 文件上传 @RequestMapping(value = "http://www.mamicode.com/uploadFile", method = RequestMethod.POST) public String uploadFile(HttpServletRequest request) throws IOException { MultipartHttpServletRequest multipartHttpServletRequest = (MultipartHttpServletRequest) request; MultipartFile file = multipartHttpServletRequest.getFile("file"); String fileName = file.getOriginalFilename(); SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyyMMddHHmmss"); String path = "F:/" + simpleDateFormat.format(new Date()) + fileName.substring(fileName.lastIndexOf(".")); OutputStream fileOutputStream = new FileOutputStream(path); InputStream inputStream = file.getInputStream(); byte[] buffer = new byte[2048]; while (inputStream.read(buffer) != -1) { fileOutputStream.write(buffer); } log.info(path); fileOutputStream.flush(); fileOutputStream.close(); inputStream.close(); return "test/success"; }
springMVC实现多文件上传
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。