在日常开发项目中,图片上传下载是经常调用的接口也是必不可少的。

首先调用文件上传接口,将文件上传到自己想要上传的本地地址中,在这里方便演示,就选取将图片上传到java项目的resource路径下upload文件中。

controller层接口代码 :

/**

* 图片上传到resource路径下 upload文件中

* @param file

* @return

* @throws IOException

*/

@PostMapping("/uploadImage")

public String uploadImage(MultipartFile file) throws IOException {

//获取上传图片全名

String filename = file.getOriginalFilename();

//截取图片后缀名

String s = filename.substring(filename.lastIndexOf("."));

//使用UUID拼接文件后缀名 防止文件名重复 导致被覆盖

String replace = UUID.randomUUID().toString().replace("-", "")+s;

//创建文件 此处文件路径为项目resource目录下upload文件中

注:不知道resource路径 可以右键resource文件选择Cpoy Path/Reference 后点击选择Path From repository Root即可

File file1 = new File(System.getProperty("user.dir") + "/springboot/src/main/resources/upload/" + replace);

//判断文件的父文件夹是否存在 如果不存在 则创建

if (!file1.getParentFile().exists()){

file1.getParentFile().mkdirs();

}

file.transferTo(file1);

System.out.println(file1.getAbsolutePath());

//返回文件访问路径

这里是在配置类中配置的访问路径,访问项目中的文件需要ip和端口号才能访问到具体的程序

return "http://localhost:9090/upload/"+filename;

}

接着需要配置静态资源过滤器,将你想要的文件访问路径映射为实际图片存储的位置,在这里 就是将返回的访问路径("http://localhost:9090/upload/"+filename)映射为实际存储的位置(UUID.randomUUID().toString().replace("-", "")+s)里:配置类代码如下:

/**

* 配置静态资源过滤器

* @param registry

*/

@Override

protected void addResourceHandlers(ResourceHandlerRegistry registry) {

//设置访问 addResourceHandler中的虚拟路径 被映射到 addResourceLocations真实路径中

registry.addResourceHandler("/upload/**")

.addResourceLocations("file:"+System.getProperty("user.dir") + "/springboot/src/main/resources/upload/");

super.addResourceHandlers(registry);

}

调用接口,上传图片结果如下: