Spring-Boot的上传

传参

前端用from表单提交,spring boot 参数已经通过拦截器做好了映射处理

文件上传配置

spring.servlet.multipart.max-request-size=500MB
spring.servlet.multipart.max-file-size=500MB

如果有覆盖总是最下面的生效

自定义配置文件

1
2
property.param.key=key
property.param.name=name

映射类

1
2
3
4
5
6
7
8
9
@Configuration
@PropertySource("classpath:self-config.properties")
@ConfigurationProperties(prefix="property.param")
@Data
@Component
public class FileProperties {
private String key;
private String name;
}

实现类

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
@EnableConfigurationProperties(FileProperties.class)
@Service
@Slf4j
public class ServiceImpl implements MultipartFileService{
private final FileProperties fileProperties;
@Autowired
@SuppressWarnings("SpringJavaAutowiringInspection")
public MultipartFileServiceImpl(FileProperties fileProperties) {
this.fileProperties = fileProperties;
}

public void test(){
log.info(fileProperties.getKey+fileProperties.getName);
}
}

文件上传实现返回上传路径

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
private String saveFile(MultipartFile file,String fileType,String fileName){
//读取配置文件,获取文件上传路径
Path path= Paths.get(fileProperties.getUploadPath(fileType)+ fileName);
File targetFile=path.toFile().getParentFile();
if(!targetFile.exists()){
targetFile.mkdirs();
}
try {
byte[] bytes = file.getBytes();
Files.write(path,bytes);
}catch (Exception e){
log.error(e.getMessage(),e);
return null;
}
return path.toString();
}