Spring Boot上传图片或文件并且进行访问(至指定盘符)

Controller层:
@Controller
public class FileController(){
//访问相应的页面
@GetMapping(value = “file”)
public String file(){
return “file”;
}
@PostMapping(value = “/uploadfile”)
public String fileUpload(@RequestParam(value = “file”) MultipartFile file, Model model, HttpServletRequest request){
Map<String,Object> map = new HashMap<>(2);
if(file.getSize()>1024102410){
map.put(“code”,500);
map.put(“message”,“文件过大,请上传10M以内的文件”);
System.out.println(“文件上传失败”);
}
String path = request.getContextPath();
String basePath = request.getScheme() + “?/” +request.getServerName() + “:” + request.getServerPort() + path;
if(file.isEmpty()){
throw new RuntimeException(“文件为空”);
}
String fileName = file.getOriginalFilename();
String suffixName = fileName.substring(fileName.lastIndexOf("."));
String filePath = “D://test//”;
File dest = new File(filePath + fileName);
if(!dest.getParentFile().exists()){
dest.getParentFile().mkdirs();
}
try{
file.transferTo(dest);
}catch (IOException e){
e.printStackTrace();
}
String filename = “/test/” + fileName;
model.addAttribute(“filename”,filename);
//输出文件的名称以及文件的大小
System.out.println(“文件:”+fileName+“的大小是:”+dest.length()/1024+“KB”);
//输出相应的访问路径
System.out.println(basePath + “/test/” + fileName);
return “file”;
}
}
配置文件:application.properties

##访问前端配置
spring.thymeleaf.prefix=classpath:/templates/
#静态资源对外暴露的访问路径
file.staticAccessPath=/test/**
#文件上传目录
file.uploadFolder=d://test/

工具类:UploadFilePathConfig**
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 UploadFilePathConfig implements WebMvcConfigurer {

@Value("${file.staticAccessPath}")
private String staticAccessPath;

@Value("${file.uploadFolder}")
private String uploadFolder;

@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
registry.addResourceHandler(staticAccessPath).addResourceLocations(“file:” + uploadFolder);
}

}
前端:file.html 位于templates下面
在这里插入图片描述

©️2020 CSDN 皮肤主题: 大白 设计师:CSDN官方博客 返回首页