spring boot 上传文件保存

版权声明:The beautiful thing about learning is nobody can take it away from you. https://blog.csdn.net/xiuye2015/article/details/89706950
//文件上传,支持单个多个文件上传,或者文件夹上传
	@PostMapping("uploadfiles")
	public Result<List<String>> file(@RequestParam("file") MultipartFile[] files, @Value("${upload.file.path}") String path,
			HttpSession session) throws IllegalStateException, IOException {

		List<String> filesPath = TypeUtil.dynamic_cast(session.getAttribute("uploadFilesUrls"));
		LogUtil.log(filesPath);
		if(Objects.isNull(filesPath)) {
			filesPath = TypeUtil.createList();
			session.setAttribute("uploadFilesUrls", filesPath);
		}
		 
		// path 可以是文件夹也可以是文件
		Path p = Paths.get(path);
		if (!Files.exists(p)) {
			Files.createDirectories(p);
		}
		for (MultipartFile file : files) {
			String filename = file.getOriginalFilename();
			LogUtil.log(filename);
			//判断文件是否有"/" ,去掉文件夹路径
			int index = filename.lastIndexOf("/");
			if(index > -1) {
				filename = filename.substring(index);
			}
			
			//获取文件后缀
			index = filename.lastIndexOf(".");
			if(index == -1) {
				index = filename.length();
			}
			
			String suffix = filename.substring(index);
			filename = UUID.randomUUID().toString() + suffix;
			p = Paths.get(path, filename);
			file.transferTo(p);
			filesPath.add("files/"+filename);
		}
		
		return ComUtil.successResult("all", filesPath, "保存文件");
	}
<form action="uploadfiles" enctype="multipart/form-data" method="POST">
    <input type="file" name='file' multiple>
    <input type="file" name='file'>
    <input type="submit">
</form>

spring.servlet.multipart.location=/temp/files
spring.servlet.multipart.max-file-size=2MB
spring.servlet.multipart.max-request-size=50MB

upload.file.path=/upload/files

#spring.mvc.static-path-pattern=/resources/**
spring.resources.static-locations=file:${upload.file.path}

猜你喜欢

转载自blog.csdn.net/xiuye2015/article/details/89706950