问题是这样,我使用IDEA创建的spring-boot框架,做了一个接收图片返回url的功能,如果服务端不停止,这个url可以访问到图片。但是,如果把服务端stop and rerun,这个url就访问不到图片了。原因我也搞明白了,是因为spring-boot内嵌tomcat,每次运行都会新建一个tomcat-docbase文件夹,所有资源都是放在这里面的。上一次上传的图片在上一次的docbase里面,所以这次运行就访问不到上一次的。但是,我虽然知道了是这样造成的,应该怎么解决呢?
附上代码:
public String upload(HttpServletRequest request, HttpServletResponse response, @RequestParam(value = "file", required = false) MultipartFile file) throws IOException {
response.setContentType("text/html;charset=utf-8");
/* 设置响应头允许ajax跨域访问 */
response.setHeader("Access-Control-Allow-Origin", "*");
/* 星号表示所有的异域请求都可以接受, */
response.setHeader("Access-Control-Allow-Methods", "GET,POST");
int id=Integer.parseInt(request.getParameter("uid"));
String name=request.getParameter("name");
String title=request.getParameter("title");
System.out.println("执行upload");
request.setCharacterEncoding("UTF-8");
System.out.println("执行图片上传");
String user = request.getParameter("user");
System.out.println("user:"+user);
if(!file.isEmpty()) {
System.out.println("成功获取照片");
String fileName = file.getOriginalFilename();
String path = null;
String type = null;
type = fileName.indexOf(".") != -1 ? fileName.substring(fileName.lastIndexOf(".") + 1, fileName.length()) : null;
System.out.println("图片初始名称为:" + fileName + " 类型为:" + type);
if (type != null) {
if ("GIF".equals(type.toUpperCase())||"PNG".equals(type.toUpperCase())||"JPG".equals(type.toUpperCase())) {
// 项目在容器中实际发布运行的根路径
String realPath = request.getSession().getServletContext().getRealPath("/");
// 自定义的文件名称
String trueFileName = String.valueOf(System.currentTimeMillis()) + fileName;
// 设置存放图片文件的路径
path=realPath+request.getContextPath()+"/"+id+name+title+"articleimages";
//path=realPath+request.getContextPath()+"/"+"articleimages";
File myPath = new File( path );
if ( !myPath.exists()){//若此目录不存在,则创建之
myPath.mkdir();
System.out.println("创建文件夹路径为:"+ path);
}
String imagepath = path+"/" + trueFileName;
System.out.println("存放图片文件的路径:" + imagepath);
file.transferTo(new File(imagepath));
System.out.println("文件成功上传到指定目录下");
String url = getTomcatUrl();
String res=url+"/"+id+name+title+"articleimages/"+trueFileName;
//String res=url+path+"/"+trueFileName;
System.out.println(res);
return res;
}else {
System.out.println("不是我们想要的文件类型,请按要求重新上传");
return "error";
}
}else {
System.out.println("文件类型为空");
return "error";
}
}else {
System.out.println("没有找到相对应的文件");
return "error";
}
}
//获取tomcat项目路径
public static String getTomcatUrl() {
HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
String basePath = request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort() + "/";
return basePath;
}