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;
        }
  • 相关阅读:
    装饰器(十五)
    静态库与动态库
    深浅拷贝(十四)
    迭代器_iter_,生成器yeild,三元运算,列表解析(十三)
    vim
    文件操作(十二)——open,read,close,write,seek,truncate
    在启用属性的情况下启动 Confluence 6
    Confluence 6 属性的一个示例
    Confluence 6 属性的一个活动
    Confluence 6 使用页面请求属性来对慢性能进行问题解决
  • 原文地址:https://www.cnblogs.com/jiangfeilong/p/11026426.html
Copyright © 2011-2022 走看看