SpringBoot文件访问映射的两种实现方式
业务需求:通过SpringBoot访问服务器(磁盘内)的所有文件,用于正常项目中上传图片(文件)的访问。
图片路径:E://images/upload/123.jpg,现在通过两种方式实现对图片的访问
方式一(推荐):
增加配置类实现WebMvcConfigurer接口,然后在addResourceHandlers方法中设置文件夹与访问路径之间的映射关系。
参考代码:
@Configuration
public class FileConfig implements WebMvcConfigurer {
public void addResourceHandlers(ResourceHandlerRegistry registry) {
registry.addResourceHandler("/upload/**").addResourceLocations("file:" + "E://images/upload/");
}
}
访问示例:
http://localhost:8080/upload/123.jpg
方式二:
专门新增一个接口作为图片(文件)访问的入口,接口中要进行编码转换,而且可以设置文件强制下载不打开
参考代码:
@RestController
@RequestMapping("/file")
public class FileController {
private static final String FILE_PATH = "E://images/upload/";
@GetMapping(value = "/static/**")
public void view(HttpServletRequest request, HttpServletResponse response) {
String imgPath = extractPathFromPattern(request);
if(StringUtil.isEmpty(imgPath) || imgPath=="null"){
return;
}
InputStream inputStream = null;
OutputStream outputStream = null;
try {
imgPath = imgPath.replace("..", "");
if (imgPath.endsWith(",")) {
imgPath = imgPath.substring(0, imgPath.length() - 1);
}
String fileUrl = FILE_PATH + imgPath;
File file = new File(fileUrl);
if(!file.exists()){
response.setStatus(404);
throw new RuntimeException("文件不存在..");
}
response.setContentType("application/force-download");// 设置强制下载不打开
response.addHeader("Content-Disposition", "attachment;fileName=" + new String(file.getName().getBytes("UTF-8"),"iso-8859-1"));
inputStream = new BufferedInputStream(new FileInputStream(fileUrl));
outputStream = response.getOutputStream();
byte[] buf = new byte[1024];
int len;
while ((len = inputStream.read(buf)) > 0) {
outputStream.write(buf, 0, len);
}
response.flushBuffer();
} catch (IOException e) {
response.setStatus(404);
e.printStackTrace();
} finally {
if (inputStream != null) {
try {
inputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (outputStream != null) {
try {
outputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
/**
* ISO-8859-1 => UTF-8 进行编码转换
*/
private static String extractPathFromPattern(final HttpServletRequest request) {
String path = (String) request.getAttribute(HandlerMapping.PATH_WITHIN_HANDLER_MAPPING_ATTRIBUTE);
String bestMatchPattern = (String) request.getAttribute(HandlerMapping.BEST_MATCHING_PATTERN_ATTRIBUTE);
return new AntPathMatcher().extractPathWithinPattern(bestMatchPattern, path);
}
}
访问示例:
http://localhost:8080/file/static/123.jpg