spring mvc 上传文件

@RequestMapping("/addoper")
    public ModelAndView addoper(@ModelAttribute("goods") Goods goods,
                          ModelAndView mv, MultipartFile pic,
                          HttpServletRequest request)
                    throws IllegalStateException, IOException {
        System.out.println("now add goods: " + goods);
        /*
         * dir 获取当前文件存放的目录地址
         * suffix 用来获取当前上传的文件的扩展名
         */
        String FILE_TARGET = "target";
        String basePath = request.getSession().getServletContext().getRealPath("/"); // "/": 表示获取根目录
        /* basePath = basePath.substring(0,basePath.lastIndexOf(FILE_TARGET)); */
        String dir = basePath + "src/main/webapp/goodsimage/";
        // 新图片的名称
        String originFileName = pic.getOriginalFilename();
        String newFileName = XXShopUtil.getId() +
                originFileName.substring(originFileName.lastIndexOf("."));
        // 新的图片
        File newFile = new File(dir + newFileName);
        // 将内存中的数据写入磁盘
        pic.transferTo(newFile);
//        String dir = ServletActionContext.getServletContext().getRealPath(
//                "/goodsimage");
//        String suffix = "";
//        String fileName = XXShopUtil.getId();
//        if (thumbnail != null) {
//            suffix = thumbnailFileName.substring(thumbnailFileName
//                    .lastIndexOf("."));
//            // 组装成最后需要保存的文件的地址(包括文件的扩展名)
//            File saveFile = new File(new File(dir), fileName + suffix);
//            try {
//                // 上传文件 org.apache.commons.io.FileUtils 既可以实现将文件上传到服务器上对应的文件夹下面
//                FileUtils.copyFile(thumbnail, saveFile);
//            } catch (IOException e) {
//            }
//            // 将文件的地址信息添加到数据库中
//            goods.setThumbnail("goodsimage/" + fileName + suffix);
//        }
        if(goods != null) {
            goods.setThumbnail("goodsimage/" + newFileName);
            goodsService.addGoods(goods);
        }

        mv.setViewName("redirect:/goods/listByPage");
        return mv;
    }
原文地址:https://www.cnblogs.com/jiangfeilong/p/11026426.html