SpringMVC上传文件路径问题

本文探讨了在Spring MVC项目中,图片上传至target目录而非预期目录的问题,并提供了两种解决方案:一是为本地资源创建虚拟路径,二是在服务器上发布资源并使用URL访问。文章详细解释了IDEA构建的Maven Web项目在Tomcat部署时,使用war exploded模式导致的图片上传路径问题。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

控制器代码如下:

发现上传的图片总是上传至项目的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中访问时,只需调用虚拟路径即可

转载于:https://www.cnblogs.com/SakalakaZ/p/9466994.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值