This article will introduce to you how to achieve multi-file upload effect in Java. It has certain reference value. Friends in need can refer to it. I hope it will be helpful to you.
Without further ado, let’s go straight to the code:
@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(); } } } }
Summary: The above is the entire content of this article, I hope it will be helpful to everyone’s learning. For more related tutorials, please visit Java video tutorial, java development graphic tutorial, bootstrap video tutorial!
The above is the detailed content of How to achieve multi-file upload effect in java (code example). For more information, please follow other related articles on the PHP Chinese website!