SpringMVC上传文件,批量上传文件

一:导入相关Jar包

commons-fileupload.jar

commons-io.jar

 

二:配置web.xml。上载解析器

<!-- 文件上传配置 -->
<bean id="multipartResolver"  class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
    <!-- 设置编码格式 -->  
    <property name="defaultEncoding" value="utf-8"></property> 
    <!-- 设置文件大小 -->  
    <property name="maxUploadSize" value="10485760000"></property>
    <!-- 设置缓冲区大小 -->  
    <property name="maxInMemorySize" value="40960"></property>  
</bean> 

 

三:web页面

<form action="upload.do" enctype="multipart/form-data" method="post">
  	文件:<input type="file" name="file"/><input type="submit" value="上传"/>
</form>

 

四:controller类 @RequestParam("file") 这个注解必须有

/**
* spring mvc封装了上传文件  将其封装为一个file对象
* */
@RequestMapping("/upload.do")
public String upload(@RequestParam("file") CommonsMultipartFile file,HttpServletRequest req){
    //获取上传位置
    String path=req.getRealPath("/upload");
    //获取文件名
    String filename=file.getOriginalFilename();
    try {
        InputStream is = file.getInputStream();
        OutputStream os = new FileOutputStream(new File(path,filename));
        int len=0;
        byte[] buffer = new byte[400];
        while((len=is.read(buffer))!=-1){
            os.write(buffer, 0, len);
        }
        os.close();
        is.close();
    } catch (FileNotFoundException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }
    return "redirect:index.jsp";
}

 

五:批量上传web页面

<form action="batch.do" enctype="multipart/form-data" method="post">
  	文件1:<input type="file" name="file"/><br>
  	文件2:<input type="file" name="file"/><br>
  	<input type="submit" value="上传"/>
</form>

 

六:批量上传controller类

@RequestMapping("/batch.do")
public String batch(@RequestParam("file") CommonsMultipartFile file[],HttpServletRequest req){
    //获取上传位置
    String path=req.getRealPath("/upload");
    for(int i=0;i<file.length;i++){
        //获取文件名
        String filename=file[i].getOriginalFilename();
        try {
            InputStream is = file[i].getInputStream();
           OutputStream os = new FileOutputStream(new File(path,filename));
           int len=0;
           byte[] buffer = new byte[400];
           while((len=is.read(buffer))!=-1){
               os.write(buffer, 0, len);
           }
           os.close();
           is.close();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    return "redirect:index.jsp";
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

EngineerForSoul

你的鼓励是我孜孜不倦的动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值