前言
这两天重新看erupt框架, 发现他设置的本地文件上传路径不在项目的指定静态文件夹下, 于是看了下他的源码, 原来它是通过重写静态资源目录设置的! 这样做可以将上传的文件与项目脱离, 不会对jar包文件产生冗余负载
示例
WebMvcConfig
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
/**
* @author 朝花不迟暮
* @version 1.0
* @date 2021/6/26 20:18
*/
@Configuration
public class WebMvcConfig implements WebMvcConfigurer
{
@Override
public void addResourceHandlers(ResourceHandlerRegistry registry)
{
registry.addResourceHandler("/**")
.addResourceLocations("classpath:/META-INF/resources/")
.addResourceLocations("classpath:/resources/")
.addResourceLocations("classpath:/static/")
.addResourceLocations("classpath:/public/");
/*解释:
/files/**: 相当于 别名的意思
file:D:/图片/: 本地文件的路径*/
registry.addResourceHandler("/files/**")
.addResourceLocations("file:D:/图片/");
// WebMvcConfigurer.super.addResourceHandlers(registry);
}
}
最关键的是下面配置
addResourceHandler:是相当于配置了一个映射
addResourceLocations:对应本地文件夹
上面的是防止之前的静态资源文件夹失效
FileController
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.UUID;
/**
* @author 朝花不迟暮
* @version 1.0
* @date 2021/6/26 20:25
*/
@RestController
public class FileController
{
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
@PostMapping("/upload")
public String upload(MultipartFile file, HttpServletRequest req)
{
// String realPath = req.getSession().getServletContext().getRealPath("/uploadFile/");
String format = sdf.format(new Date());
// File folder = new File(realPath + format);
File folder=new File("D:/图片/"+format);
if (!folder.isDirectory())
{
if (!folder.mkdirs())
{
return "文件夹创建失败";
}
}
String oldName = file.getOriginalFilename();
assert oldName != null;
String newName = UUID.randomUUID().toString() + oldName.substring(oldName.lastIndexOf("."));
try
{
file.transferTo(new File(folder, newName));
//以上都是普通代码, 这里的/files/ 对应的就是你在WebMvcConfig设置的地址映射
return req.getScheme() + "://" + req.getServerName() + ":" + req.getServerPort() + "/files/" + format + newName;
} catch (IOException e)
{
e.printStackTrace();
}
return "上传失败!";
}
}
这里的/files/ 对应的就是你在WebMvcConfig设置的地址映射
静态文件
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>上传界面</title>
</head>
<body>
<form action="/upload" method="post" enctype="multipart/form-data">
<input type="file" name="file" value="请选择文件">
<input type="submit" value="上传">
</form>
</body>
</html>
测试
访问:http://localhost:8080/upload.html
选择图片上传后返回地址
浏览器访问