通过http请求服务资源
springboot有一个目录:static这个目录其实就是静态资源目录,这个目录下面的文件是可以通过http直接问题的。但是程序话一般打成jar包,我们没办法去文件写入到这个static下,所以springboot提供静态资源目录的额外的映射机制,就是静态资源服务映射。它就类似于:nginx的静态资源映射。
需要实现WebMvcConfigurer接口
@Configuration
public class WebMvcConfiguration implements WebMvcConfigurer {
@Value("${file.staticPatternPath}")
private String staticPatternPath;
@Value("${file.uploadFolder}")
private String uploadFolder;
@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
//registry.addResourceHandler("访问的路径").addResourceLocations("上传资源的路径");
//注意: uploadFolder 后面一定跟/ 如 E:/test/ 如果E:/test 就会出现404
registry.addResourceHandler(staticPatternPath).addResourceLocations("file:"+uploadFolder);
}
}
配置文件:
#注意每个访问路径后面的路径加 /
file:
uploadFolder: E:/test/
staticPath: http://localhost:8888/
staticPatternPath: /uploadFile/**
控制层:
@RequestMapping("/upload/file")
@ResponseBody
public String uploadImg(@RequestParam("file") MultipartFile multipartFile){
if (multipartFile.isEmpty()){
return "文件有误";
}
return uploadService.uploadFile(multipartFile); //application/x-msdownload
}
service
@Value("${file.uploadFolder}")
private String uploadFolder; //具体位置
@Value("${file.staticPath}")
private String staticPath; //http://localhpst:8080
/**
*MultipartFile 这个对象是springmvc提供的文件上传的接受的类
* 他的底层自动会和HttpServletRequest request 中的request.getInputStream融合
* 从而达到文件上传的效果,也就是告诉我们一个道理
* 文件上传的底层原理request.getInputStream
* @param multipartFile
* @return
*/
public String uploadFile(MultipartFile multipartFile){
try {
//文件名字
String filename = multipartFile.getOriginalFilename();
//文件后缀
String suffix = filename.substring(filename.lastIndexOf("."));
// 生成的唯一的文件名:能不能用中文名:不能因为统一用英文命名。
String newFileName = UUID.randomUUID().toString() + suffix;
//日期目录
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd");
String format = dateFormat.format(new Date());//2021/11/03
//指定文件上传的目录
String targetPath = uploadFolder + format;
File file = new File(targetPath);
// 如果目录不存在 递归创建
if (!file.exists())
file.mkdirs();
//指定文件上传以后的服务器的完整的文件名
File targetFileName = new File(targetPath,newFileName);
//文件上传到指定的目录
multipartFile.transferTo(targetFileName);
//可访问的路径要返回页面
// http://localhpst:8888/uploadFile/2021/10/27/5f61dea2-4b77-4068-8d0b-fdf415eac6df.png
//文件所在的目录和文件名(生成的)
String filename1 = format + "/"+newFileName;
return staticPath+"uploadFile/"+filename1;
} catch (IOException e) {
e.printStackTrace();
return "faile";
}
}
文件上传成功返回一个结果
下面两张图结合一起来看就可以得出结论。结论在图片中
以上内容属于个人笔记整理,如有错误,欢迎批评指正