spring-boot项目中文件上传,使用传统的方法是不可以的。需要通过映射获取文件,在页面显示或者是下载
1.yml配置
file:
#服务器地址
uploadurl: "/upload/file/" // 最后一个'/' 不能
#本地地址
#localurl: "D:/upload/resource/file/"
注意:地址最后面的’/’ 一定不要忘记!!
2.文件上传
@Value("${file.uploadUrl}")
public String path;
@PostMapping("/test")
public void test(MultipartFile file,HttpServletRequest request) throws IOException {
//获取文件名
String oldName = file.getOriginalFilename();
String suffix = oldName.substring(oldName.lastIndexOf(".") + 1);
String newName = UUID.randomUUID().toString() +"."+ suffix;
File file1 = new File(path,newName);
if (!file1.exists()) {
file1.mkdirs();
}
// 保存文件
file.transferTo(file1);
}
3.配置路劲映射
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
@Configuration
public class FileConfig implements WebMvcConfigurer {
@Value("${file.uploadUrl}")
private String fileUrl;
public void addResourceHandlers(ResourceHandlerRegistry register){
register.addResourceHandler("/file/**") // 访问路劲
.addResourceLocations("file:"+fileUrl); // 资源真实路径
}
}
注意:配置本地上传地址或者服务器地址,springboot项目可以通过映射获取文件,从而页面显示
4.访问:项目访问路径+配置的映射访问路径