Controller获得上传文件的绝对路径

来源:互联网 发布:mysql 多主多从 编辑:程序博客网 时间:2024/05/18 01:44
    @RequestMapping(value = "/upload", method = RequestMethod.POST)    public ModelAndView onSubmit(HttpServletRequest request,            HttpServletResponse response) throws Exception {        MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;        SimpleDateFormat dateformat = new SimpleDateFormat("yyyy/MM/dd/HH");        /** 构建文件保存的目录* */        String logoPathDir = "/business/shops/upload/"                + dateformat.format(new Date());        /** 得到文件保存目录的真实路径* */        String logoRealPathDir = request.getSession().getServletContext()                .getRealPath(logoPathDir);        /** 根据真实路径创建目录* */        File logoSaveFile = new File(logoRealPathDir);        if (!logoSaveFile.exists())            logoSaveFile.mkdirs();        /** 页面控件的文件流* */        MultipartFile multipartFile = multipartRequest.getFile("file");        /** 获取文件的后缀* */        String suffix = multipartFile.getOriginalFilename().substring(                multipartFile.getOriginalFilename().lastIndexOf("."));        /** 使用UUID生成文件名称* */        String logImageName = UUID.randomUUID().toString() + suffix;// 构建文件名称        /** 拼成完整的文件保存路径加文件* */        String fileName = logoRealPathDir + File.separator + logImageName;        File file = new File(fileName);        try {            multipartFile.transferTo(file);        } catch (IllegalStateException e) {            e.printStackTrace();        } catch (IOException e) {            e.printStackTrace();        }        /** 打印出上传到服务器的文件的绝对路径* */        System.out.println("****************"+fileName+"**************");        insertDate(fileName);        return new ModelAndView("redirect:/business/shops/my.jsp");    }