使用MultipartResolver上传图片

使用MultipartResolver上传图片

话不多说直接上代码

controller

@RequestMapping("add.action")
    public String addNewser(Model model, HttpSession session,MultipartFile upload, Newser newser, HttpServletRequest request) throws IOException {
        newser.setNewseruser((User) session.getAttribute("success"));
        //判断upload是否为空
        if (!upload.isEmpty()) {
            //1.getRealPath得到当前项目根目录
            String uploadFilePath =request.getServletContext().getRealPath("/");
            //2.自定义文件夹名称(照片的文件夹)
            String folder = "/upload";
            //3.合到一起1+2
            String route = uploadFilePath+folder;
            //4.使用UUID自定义吗、照片名称
            String fileName = UUID.randomUUID().toString();
            //5.获得原始名称
            String oriName = upload.getOriginalFilename();
            //6.获取后缀名
            String suffix = oriName.substring(oriName.lastIndexOf("."));
            //7.新建File对象
            File file = new File(uploadFilePath + folder);
            //8.判断文件夹是否存在如果不存在创建
            if (!file.exists()) {
                file.mkdirs();
            }
            //9.以文件后缀名判断是否符合图片文件格式
            if (suffix.equalsIgnoreCase(".jpeg") || suffix.equalsIgnoreCase(".jpg") || suffix.equalsIgnoreCase(".png") || suffix.equalsIgnoreCase(".gif")) {
                //10.文件重命名
                String newName = fileName + suffix;
                //11.传输
                upload.transferTo(new File(route,newName));
                //12.传入对象
                newser.setPicPath(newName);
            }
        }
        List<News> nt=newsService.queryAll();
        model.addAttribute("nt",nt);
        model.addAttribute("newser",newser);
        newserService.saveorupdate(newser);
        return "redirect:index.action";
    }

xml

 <bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
        <property name="defaultEncoding" value="UTF-8"/>
        <property name="maxUploadSize" value="10240000" />
        <property name="maxInMemorySize" value="4096"/>
    </bean>
  • 2
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 3
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值