SpringBoot实现文件上传
作者:互联网
html代码
<div> <form role="form" method="post" enctype="multipart/form-data" th:action="@{/upload}"> <div> <label>File input</label> <input type="file" id="exampleInputFile" name="file_upload"> </div> <div> <label>Batch File input</label> <input type="file" id="batchInputFile" name="files_upload" multiple> </div> <button type="submit" class="btn btn-primary">Submit</button> </form> </div>
Controller代码
@PostMapping("/upload") public String fileUpload(@RequestParam String email, @RequestParam String password, @RequestPart MultipartFile file_upload,@RequestPart MultipartFile[] files_upload) throws IOException { if (!file_upload.isEmpty()) { String originalFilename = file_upload.getOriginalFilename(); // UUID随机生成新文件名 String newFileName = UUID.randomUUID().toString().replaceAll("-", "") + originalFilename.substring(originalFilename.lastIndexOf(".")); file_upload.transferTo(new File("D:\\" + newFileName)); } if (files_upload.length > 0) { for (MultipartFile file : files_upload) { if (!file.isEmpty()) { String originalFilename = file.getOriginalFilename(); // UUID随机生成新文件名 String newFileName = UUID.randomUUID().toString().replaceAll("-", "") + originalFilename.substring(originalFilename.lastIndexOf(".")); file.transferTo(new File("D:\\" + newFileName)); } } } return "form/form_layouts"; }
标签:文件,String,upload,UUID,newFileName,file,上传,originalFilename,SpringBoot 来源: https://www.cnblogs.com/prettychandler/p/16168233.html