目前需要完成一个功能,通过添加一个文件后
选择之后得到路径和名字
点击添加json文件后成功将数据保存到数据库
此时可以通过浏览器访问http://localhost:9002/model/470b9bb03b8e11ebab91bd49b27fb332/+文件名 来访问到E:\共享文件\综合井场布\场布实景下的所有文件,根据我的理解,应该是把这个路径成功的映射成为静态资源,才能这样访问,但是没有明白这个是怎么不用重启就能通过一个路径动态映射静态资源,正常来我用springboot配置外部静态资源映射的话只能先指定路径
package com.earthadmin.config;
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.WebMvcConfigurationSupport;
/**
* @author
* @date 2020/12/08 9:56
*/
@Configuration
public class WebMvcConfiguration extends WebMvcConfigurationSupport {
/**
* 匹配url 中的资源映射
*/
@Value("${accessFile.resourceHandler}")
private String resourceHandler;
/**
* 上传文件保存的本地目录
*/
@Value("${accessFile.location}")
private String location;
/**
* 配置静态资源映射
*
* @param registry
*/
@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
registry.addResourceHandler("/**").addResourceLocations("classpath:/META-INF/resources/") .addResourceLocations("classpath:/resources/").addResourceLocations("classpath:/static/")
.addResourceLocations("classpath:/public/");
registry.addResourceHandler(resourceHandler).addResourceLocations("file:///" + location);
super.addResourceHandlers(registry);
}
}
后来研究了nginx的动静分离,发现一样都要先指定路径,而且好像也不能和jedis一样可以在springboot项目里操作nginx改配置文件和重启,所以用nginx应该也行不通,然后尝试拦截url来转发
package com.earthadmin.filter;
/**
* @author lanxifang
* @date 2020/12/07 18:51
*/
import com.earthadmin.mapper.ModelsMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.core.annotation.Order;
import javax.annotation.Resource;
import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
/**
* Servlet Filter implementation class HttpFilter
*/
@WebFilter(filterName="CORSFilter",urlPatterns="/*")
@Order(value = 1)
@Slf4j
public class CORSFilter implements Filter {
@Resource
private ModelsMapper modelsMapper;
/**
* Default constructor.
*/
public CORSFilter() {
// TODO Auto-generated constructor stub
}
/**
* @see Filter#destroy()
*/
@Override
public void destroy() {
// TODO Auto-generated method stub
}
/**
* 解决跨域
* @see Filter#doFilter(ServletRequest, ServletResponse, FilterChain)
*/
@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
HttpServletResponse resp=(HttpServletResponse)response;
HttpServletRequest rep = (HttpServletRequest) request;
resp.setHeader("Access-Control-Allow-Origin", rep.getHeader("Origin"));
resp.setHeader("Access-Control-Allow-Methods", "POST, GET,PUT, OPTIONS, DELETE,PUT");
resp.setHeader("Access-Control-Allow-Headers", "x-requested-with,Authorizationaccept, origin, content-type, token");
//允许跨域请求中携带cookie
resp.setHeader("Access-Control-Allow-Credentials","true");
String path = rep.getServletPath();
log.info("------------------------------------path"+path);
// if(path.endsWith(".json")||path.endsWith(".b3dm") ||path.endsWith(".glb")){
// log.info("------------------------------------这是一个访问静态资源的请求");
//
// // 这是url例子/model/c7cc1730388111ebbc661d14fb544ab5/top/0_0_0_0.b3dm
// String[] str = StringUtils.split(path,"/");
// //strurl[1]就是要获取的id
// log.info("------------------------------------从url获取的id:"+str[1]);
// Model modelById = modelsMapper.findModelById(str[1]);
//
// log.info("new File(modelById.getPath()).getParent()="+new File(modelById.getPath()).getParent());
// String oldUrl = "/"+str[0]+"/"+ modelById.get_id();
// // String newUrl = new File(modelById.getPath()).getParent() ;
// String newUrl = "localhost:8080";
// String resourceUrl = StringUtils.replace(path, oldUrl, newUrl).replace("\\","/");
// log.info("------------------------------------最终url="+"file:///"+resourceUrl );
// rep.getRequestDispatcher(resourceUrl).forward(rep,resp);
// RestTemplate restTemplate = new RestTemplate();
//
// System.out.println("----");
// }else {
chain.doFilter(request, response);
// }
}
/**
* @see Filter#init(FilterConfig)
*/
@Override
public void init(FilterConfig fConfig) throws ServletException {
// TODO Auto-generated method stub
}
}
理所当然行不通,最后还是没有想到怎么实现,采用整个文件夹上传的方式来完成这个功能
/**
* 上传瓦片模型
* @param folder 整个文件夹一起上传
* @return
*/
@ApiOperation("上传瓦片模型")
@ApiImplicitParams({
@ApiImplicitParam(name = "files", value = "多个文件", allowMultiple = true, dataType = "__file")
})
@PostMapping("/uploadModels")
public ResultEntity uploadFolder(MultipartFile[] folder) {
String[] split = folder[0].getOriginalFilename().split("/");
String name = split[0];
String path = location+name+"tileset.json";
String id = addModel(name, path);
if("".equals(id)){
return ResultEntity.error();
}
FileUtils.saveMultiFile(location, folder,id);
return ResultEntity.success();
}
/**
* 将model保存在数据库
* @param name 文件名
* @param path 文件路径
* @return
*/
public String addModel(String name,String path){
Model model = new Model();
model.setName(name);
model.setPath(path);
model.setType("file");
int result = modelService.addModel(model);
if(result!=1){
return "";
}
return model.get_id();
}
package com.earthadmin.Utils;
import org.springframework.web.multipart.MultipartFile;
import java.io.File;
import java.io.IOException;
/**
* @author lanxifang
* @date 2020/12/11 15:38
*/
public class FileUtils {
public static void saveMultiFile(String basePath, MultipartFile[] files,String id) {
if (files == null || files.length == 0) {
return;
}
if (basePath.endsWith("/")) {
basePath = basePath.substring(0, basePath.length() - 1);
}
for (MultipartFile file : files) {
String substring = file.getOriginalFilename().substring(file.getOriginalFilename().indexOf("/"));
String filePath = basePath + "/" +id+"/"+ substring;
makeDir(filePath);
File dest = new File(filePath);
try {
file.transferTo(dest);
} catch (IllegalStateException | IOException e) {
e.printStackTrace();
}
}
}
/**
* 确保目录存在,不存在则创建
* @param filePath
*/
private static void makeDir(String filePath) {
if (filePath.lastIndexOf('/') > 0) {
String dirPath = filePath.substring(0, filePath.lastIndexOf('/'));
File dir = new File(dirPath);
if (!dir.exists()) {
dir.mkdirs();
}
}
}
}
目前水平太低,暂时将疑惑记录一下待解决