• 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;
        }
  • 相关阅读:
    设计模式:组合模式
    对技术的认识及思考
    设计模式:策略模式
    java集合:常用集合的数据结构
    设计模式:代理模式
    java反射
    Spring事务管理
    在Spring使用junit注解进行单元测试
    tomcat限制ip访问
    获取openid回调两次
  • 原文地址:https://www.cnblogs.com/jiangfeilong/p/11026426.html
Copyright © 2020-2023  润新知