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;
        }
  • 相关阅读:
    (4.15)存储DAS,NAS,SAN在数据库存储上的应用
    (4.14)存储:RAID在数据库存储上的应用
    关于like %%的优化思路
    (4.13)SQL Server profile使用、数据库优化引擎顾问使用
    图形界面执行计划图标释义
    (4.15)全文索引的使用
    倒排索引/全文搜索基本原理
    SQLServer: 用 ApexSQLLog 恢复 SQL Server 数据
    (4.12)2012及以上列存储索引
    教你管理SQL实例系列(1-15)
  • 原文地址:https://www.cnblogs.com/jiangfeilong/p/11026426.html
Copyright © 2011-2022 走看看