java获取图片文件返回地址

private String uploadFile(HttpServletRequest req,String file_name){
        try {
            MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) req;
            // 获得文件:
            MultipartFile file = multipartRequest.getFile(file_name);
            String fileExtName = file.getOriginalFilename().substring(file.getOriginalFilename().indexOf(".") + 1);
            if(StringUtils.isEmpty(fileExtName)){
                return "";
            }
            String realPath = req.getSession().getServletContext().getRealPath("");
            String fileName = DateTimeUtil.getDateTime2Str3S4() + "." + fileExtName;
            String imgPath = "upload"+File.separatorChar+"advImg" + File.separatorChar + fileName;
            String imgPathRealPath = realPath + File.separatorChar+ "upload"+File.separatorChar+"advImg" + File.separatorChar + fileName;
            File fi = new File(imgPathRealPath);

            if (!fi.exists()) {
                fi.mkdirs();
            }
            file.transferTo(fi);
            
            return imgPath;
        } catch (Exception e) {
            return "";
        }
    }

 

posted @ 2015-06-17 10:01  坏气  阅读(1815)  评论(0编辑  收藏  举报