zoukankan      html  css  js  c++  java
  • 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;
        }
  • 相关阅读:
    多版本node安装197
    linux 测试麦克风197
    解决linux写入ntfs盘时报错:只读文件系统197
    freemarker 解析纯json字符串197
    manjaro mysql安装197
    manjaro安装微信197
    manjaro 安装输入法197
    strings包 — 汇总
    proc 目录介绍
    learning、trying、teaching
  • 原文地址:https://www.cnblogs.com/jiangfeilong/p/11026426.html
Copyright © 2011-2022 走看看