使用Spring MVC实现文件上传

spring MVC将上传文件绑定到MultipartFile对象中,并通过该
对象完成文件上传操作

相关jar文件

链接:http://pan.baidu.com/s/1kVOhZXt 密码:1647


使用Spring MVC实现单文件上传

配置springmvc-servlet.xml
在原有的xml配置中添加

<bean id="multipartResolver" 
        class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
        <property name="maxUploadSize" value="5000000"/>
         <property name="defaultEncoding" value="UTF-8"/>
    </bean>

创建jsp页面
注意别漏了:enctype=”multipart/form-data”

 <body>
    <form action="file" method="post" enctype="multipart/form-data">
        <label for="a_path">照片:</label>
        <input type="file" name="a_path" id="a_path">
        <button type="submit">上传</button>
    </form>
  </body>

编写相应的controller类

/*required=false
     * 设置文件上传不是必须的
     * 
     */
    @RequestMapping("/file")
    public String resolver(HttpSession session,
                         HttpServletRequest request,
                    @RequestParam(value="a_path",required=false) MultipartFile attach){
        //判断文件是否为空
        if(!attach.isEmpty()){
            //定义上传文件路径
            /*
             * File.separator
             * Windows、Linux自适应路径分隔符
             * 底入侵性代码实现
             */
            String path = request.getSession().getServletContext().getRealPath("statics"+File.separator+"uploadfiles");
            //获取源文件名
            String oldFileName = attach.getOriginalFilename();
            //得到文件后缀
            String prefix = FilenameUtils.getExtension(oldFileName);
            int filesize = 500000;
            if(attach.getSize()>filesize){
                System.out.println("上传大小不能超出500k");
                return "file";
            }else if(prefix.equalsIgnoreCase("jpg")
                    ||prefix.equalsIgnoreCase("jpeg")
                    ||prefix.equalsIgnoreCase("png")
                    ||prefix.equalsIgnoreCase("pneg")){
                //定义件名:当前系统时间+随机数+personal.jpg
                /*
                 *必须对上传文件进行重命名
                 *原因:
                 *  原文件名存在中文
                 *  原文件名对服务上已有文件重名 
                 */
                String fileName = System.currentTimeMillis()
                        +RandomUtils.nextInt(10000)+"personal.jpg";
                //定义file对象
                File targetFile = new File(path,fileName);
                //判断文件是否存在
                if(!targetFile.exists()){
                    //创建
                    targetFile.mkdirs();
                }
                try {
                    attach.transferTo(targetFile);
                    //输入文件路径+自适应路径分隔符(/)+文件名
                    String idPath = path+File.separator+fileName;
                    System.out.println(File.separator);
                    System.out.println(idPath);
                } catch (Exception e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                    System.out.println("文件上传失败");
                    return "file";
                }
            }else{
                System.out.println("上传图片格式不正确");
                return "file";
            }
        }
        return "file";
    }

使用Spring MVC实现多文件上传

修改jsp页面

<body>
  <!-- 文件name一致,以数组形式提交到后台 -->
    <form action="file2" method="post" enctype="multipart/form-data">
        <label for="a_path">照片1:</label>
        <input type="file" name="a_path" id="a_path">
        <label for="a_path2">照片2:</label>
        <input type="file" name="a_path" id="a_path2">
        <button type="submit">上传</button>
    </form>
  </body>

修改controller类

@RequestMapping("/file2")
    public String resolver2(HttpSession session,
                         HttpServletRequest request,
                    @RequestParam(value="a_path",required=false) MultipartFile[] attachs){
        for (int i = 0; i < attachs.length; i++) {
            MultipartFile attach = attachs[i];
            //判断文件是否为空
            if(!attach.isEmpty()){
                //定义上传文件路径
                /*
                 * File.separator
                 * Windows、Linux自适应路径分隔符
                 * 底入侵性代码实现
                 */
                String path = request.getSession().getServletContext().getRealPath("statics"+File.separator+"uploadfiles");
                //获取源文件名
                String oldFileName = attach.getOriginalFilename();
                //得到文件后缀
                String prefix = FilenameUtils.getExtension(oldFileName);
                int filesize = 500000;
                if(attach.getSize()>filesize){
                    System.out.println("上传大小不能超出500k");
                    return "file";
                }else if(prefix.equalsIgnoreCase("jpg")
                        ||prefix.equalsIgnoreCase("jpeg")
                        ||prefix.equalsIgnoreCase("png")
                        ||prefix.equalsIgnoreCase("pneg")){
                    //定义件名:当前系统时间+随机数+personal.jpg
                    /*
                     *必须对上传文件进行重命名
                     *原因:
                     *  原文件名存在中文
                     *  原文件名对服务上已有文件重名 
                     */
                    String fileName = System.currentTimeMillis()
                            +RandomUtils.nextInt(10000)+"personal.jpg";
                    //定义file对象
                    File targetFile = new File(path,fileName);
                    //判断文件是否存在
                    if(!targetFile.exists()){
                        //创建
                        targetFile.mkdirs();
                    }
                    try {
                        attach.transferTo(targetFile);
                        //输入文件路径+自适应路径分隔符(/)+文件名
                        String idPath = path+File.separator+fileName;
                        System.out.println("第"+i+"个文件"+idPath);
                    } catch (Exception e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                        System.out.println("文件上传失败");
                        return "file";
                    }
                }else{
                    System.out.println("上传图片格式不正确");
                    return "file";
                }
            }
        }


        return "file";
    }
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值