tomcat配置虚拟路径上传文件、图片

一、tomcat配置

1、在tomcat安装目录下找到conf目录(tomcat/conf/service.xml),修改service.xml文件:

path:虚拟路径,以 / 开头;

docBase:磁盘路径(绝对路径),Windows环境以盘符(D:/template)开始,linux环境如下;

reloadable:为 true 时 当web.xml或者class有改动的时候都会自动重新加载不需要从新启动服务;

<Context path="/template" docBase="/home/template" reloadable="true" />

注:增加的配置需放在<Host></Host>标签内;

建议docBase的路径不要和tomcat放在一起,首先因为配置虚拟路径就是想做资源服务器,将资源独立出来,放到项目或tomcat中就和将资源放到项目中一样,其次会增加tomcat的负载;

2、上传

上传资源时需要将资源上传到docBase(绝对路径)路径下

   @RequestMapping(value = "uploadImg", produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    @ResponseBody
    public Object uploadImg(MultipartFile file, HttpSession session, HttpServletRequest request) {
        SessionContainer s = (SessionContainer) session.getAttribute("sc");
        ResultVo resultVo = new ResultVo();
        resultVo.setCode(ResultEnum.ERROR.getCode());
//        String call_path = Global.getProperty("VOUCHER_IMAGE_URL");
        String call_path = "/template";
//        String path = Global.getProperty("VOUCHER_IMAGE_DIR");
        String path = "/home/template/";
        try {
            String fileName = file.getOriginalFilename();
            String date = com.ronglian.bms.commons.utils.DateUtil.getDate("yyyyMMdd");
            String rand = RandomUtil.randomNumbers(3);
            String merchNo = s.getMerchNo();
            if (StringUtils.isBlank(merchNo)) {
                merchNo = Constants.ROOT_ORG_CODE;
            }
            String lastStr = fileName.substring(fileName.lastIndexOf("."));
            path = path + merchNo + "/";
            fileName = date + rand + lastStr;
            File dir = new File(path, fileName);
            if (!dir.exists()) {
                dir.mkdirs();
            }
            dir.setWritable(true, false);
            file.transferTo(dir);
            // 图片物理路径
            String phy_path = dir.getPath();
            // 图片访问路径
            String filePath = call_path + "/" + merchNo + "/" + fileName;
            logger.info("图片真实路径:" + phy_path);
            logger.info("上传成功,模板路径:" + filePath);
            resultVo.setCode(ResultEnum.SUCCESS.getCode());
            resultVo.setMsg(filePath);
        } catch (IOException e) {
            logger.error("上传出错,原因:", e);
        }
        return resultVo;
    }

filePath:图片回显路径需要用虚拟路径,如:http://ip:port/template/图片.jpg

3、保存及回显

将图片路径保存到数据库,可保存两个,一个图片真实的物理路径,一个为图片的虚拟路径,或只存图片虚拟路径即可;

注:tomcat配置的虚拟路径中没有配置项目名称,一般项目的资源访问都有项目名,此时需要将项目名称去掉,或者再tomcat中配置虚拟路径时将项目名称配置进去即可。

猜你喜欢

转载自www.cnblogs.com/fatTmonkey/p/11571967.html