文件上传
spring 文件上传
- 导包
<!-- 文件上传--> <dependency> <groupId>commons-io</groupId> <artifactId>commons-io</artifactId> <version>2.11.0</version> </dependency> <dependency> <groupId>commons-fileupload</groupId> <artifactId>commons-fileupload</artifactId> <version>1.5</version> </dependency>
- 编写接口
@Controller public class UploadController { @PostMapping("/upload") @ResponseBody public Result add(@RequestParam("file") MultipartFile multipartFile, HttpServletRequest req) throws IOException { String newFileName = ""; if (multipartFile != null && !multipartFile.isEmpty()) { /** * 设置文件上传的地址 uploadPath */ String uploadPath = req.getServletContext().getRealPath("./") + "/upload"; /** * 对文件名进行操作防止文件重名 */ //1,获取原始文件名 String originalFilename = multipartFile.getOriginalFilename(); //2,截取源文件的文件名前缀,不带后缀 String fileNamePrefix = originalFilename.substring(0, originalFilename.lastIndexOf(".")); //3,加工处理文件名,原文件加上时间戳 String newFileNamePrefix = fileNamePrefix + System.currentTimeMillis(); //4,得到新文件名 newFileName = newFileNamePrefix + originalFilename.substring(originalFilename.lastIndexOf(".")); File file = new File(uploadPath, newFileName); /** * 文件上传 */ multipartFile.transferTo(file); /** * 文件复制 */ /** * webUploadPath 上传到web目录下的upload */ String webUploadPath = uploadPath.split("out")[0] + "/web/" + "upload" + "/"; createDirectory(webUploadPath); /** * 原文件路径 */ Path filePath = file.toPath(); /** * 目标路径位置 */ Path webPath = Paths.get(webUploadPath); Files.copy(filePath,webPath.resolve(filePath.getFileName())); } return Result.getInstance(1, "/upload/" + newFileName); } private void createDirectory(String uploadPath) { // 如果目录不存在则创建 File uploadDir = new File(uploadPath); if (!uploadDir.exists()) { uploadDir.mkdir(); } } }
文件高级复制
使用Path和Files
调用Files的方法 copy,使用Path 进行数值获取
使用示例:假设我们要将文件复制到目录中,给出与源文件相同的文件名:
Path source = ... Path newdir = ... Files.copy(source, newdir.resolve(source.getFileName());
参数
source
- 要复制的文件的路径
target
- 目标文件的路径(可能与源路径的不同提供程序相关联)
options
- 指定副本应如何完成的选项