SpringMVC上传文件路径问题
控制器代码如下:
发现上传的图片总是上传至项目的target目录中去,并且在jsp页面无法访问图片资源
@Controller public class FileUploadController { @Autowired ServletContext context; @RequestMapping(value="/fileUploadPage",method=RequestMethod.GET) public ModelAndView fileUploadPage(){ FileModel file=new FileModel(); ModelAndView modelAndView=new ModelAndView("fileUpload","command",file); return modelAndView; } @RequestMapping(value="/fileUploadPage",method=RequestMethod.POST) public String fileUpload(@Validated FileModel file, BindingResult result,ModelMap model,HttpServletRequest request) throws Exception{ if (result.hasErrors()){ System.out.println("validation errors"); return "fileUploadPage"; }else { System.out.println("Fetching file"); MultipartFile multipartFile=file.getFile(); String uploadPath=request.getSession().getServletContext().getRealPath("")+File.separator+"tmp"+File.separator; System.out.println("FileUploadController::Picpath::"+uploadPath); FileCopyUtils.copy(file.getFile().getBytes(), new File(uploadPath+file.getFile().getOriginalFilename())); String fileName = multipartFile.getOriginalFilename(); model.addAttribute("filepath", "/pic/"+fileName); return "success"; } }
success.jsp
<%-- Created by IntelliJ IDEA. User: sakal Date: 2018/8/12 Time: 9:02 To change this template use File | Settings | File Templates. --%> <%@ page contentType="text/html;charset=UTF-8" language="java" %> <%@ taglib prefix="form" uri="http://www.springframework.org/tags/form"%> <%@ page isELIgnored="false"%> <html> <head> <title>上传成功</title> </head> <body> 文件名称:<b>${filepath}</b>-上传成功~ <img src="${filepath}"> </body> </html>
运行结果:能成功上传图片,但无法在jsp页面访问已上传的图片
在网上找了很久,终于知道原因:
首先为什么上传的目录是target呢?因为getRealPath("") 是获取项目运行目录的路径 在这个demo中,我使用idea构建的mavenweb项目
使用Tomcat部署时,默认使用了war exploded模式
具体原因查看
IDEA Tomcat部署时war和war exploded区别
转自:https://www.cnblogs.com/JAYIT/p/8881333.html
如何在jsp中访问本地资源?
1.为本地资源创建虚拟路径
2.将资源发布在服务器上,使用url访问
我使用了第一种方法,idea操作如下:
在jsp中访问时,只需调用虚拟路径即可