本篇文章就给大家介绍java实现多文件上传效果的方法。有一定的参考价值,有需要的朋友可以参考一下,希望对你们有所帮助。
废话不多说,直接上代码:
@ApiOperation(value = "批量上传", notes = "批量上传", httpMethod = "POST") @PostMapping(value = "/upload") public void upload(HttpServletRequest request) { MultipartHttpServletRequest multipartRequest=(MultipartHttpServletRequest)request; String savePath="E:/test/"; //保证目录存在 File dir = new File(savePath); if (!dir.isDirectory()) { dir.mkdirs(); } Iterator<String> it = multipartRequest.getFileNames(); while (it.hasNext()) { MultipartFile multipartFile = multipartRequest.getFile(it.next()); if (multipartFile != null) { String originName = multipartFile.getOriginalFilename(); int subIdx = originName.lastIndexOf("."); String suffix = originName.substring(subIdx);//文件后缀 File file; String showName; while (true) { showName = UUID.randomUUID().toString().replaceAll("-", "") + suffix;//文件名称 file = new File(savePath + showName); if (!file.exists()) { break; } } byte[] buffer = new byte[1024]; try (OutputStream os = new FileOutputStream(file); InputStream is = multipartFile.getInputStream()){ while (is.read(buffer) != -1) { os.write(buffer); } } catch (IOException e) { e.printStackTrace(); } } } }
总结:以上就是本篇文的全部内容,希望能对大家的学习有所帮助。更多相关教程请访问Java视频教程,java开发图文教程,bootstrap视频教程!
以上是java如何实现多文件上传效果(代码实例)的详细内容。更多信息请关注PHP中文网其他相关文章!