springmvc上传文件路径处理

这里讨论数据库里保存的路径的相关处理,上传过程省略,可参考http://blog.csdn.net/cheung1021/article/details/7084673/
目标希望保存在项目的webapp的resources/images/upload目录下

    @RequestMapping(value = "upload", method = RequestMethod.POST)
    @ResponseBody
    public Object uploadImg(MultipartFile file, HttpServletRequest request) throws Exception {
//      String basePath = request.getSession().getServletContext().getRealPath("upload");
        //如果这样写,路径中会带有盘符D:*****,保存到数据库时应该保存为相对地址,所以不应该这样写

        String basePath = "src/main/webapp/resources/images/upload/";//如果写为"/项目名、resources/images/***"则也是保存在该盘的根目录下,所以这里写项目的相对路径,但是在保存数据库时进行路径的截取

        Calendar calendar = Calendar.getInstance();
        String year = calendar.get(Calendar.YEAR) + "";
        String month = calendar.get(Calendar.MONTH) + "";
        String uploadTargetPath = basePath + year + month + "/";    //文件目录地址,年月作为文件夹名称

        String originalFileName = file.getOriginalFilename();
        String fileType = originalFileName.substring(originalFileName.indexOf(".") + 1);
        logger.info("------------>>>>" + fileType);
        String newFileName = UUID.randomUUID().toString() + "." + fileType;
        File targetFile = new File(uploadTargetPath, newFileName);

        if(!targetFile.exists()) {
            new File(uploadTargetPath).mkdirs();
        }

        String pathForDb = uploadTargetPath.substring(uploadTargetPath.indexOf("resources"));//截取希望保存到数据库的路径
        UploadFileDto fileDto = new UploadFileDto(BG_IMG_KEY, originalFileName, 
                newFileName, pathForDb + newFileName, fileType);
        systemService.addOrUpdateImg(fileDto);
        file.transferTo(targetFile);
        return "上传成功";
    }

这种方法只是自己的一个想法,不一定成熟,希望大神指正。

  • 2
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值