stringMVC_09文件批量上传

本文介绍了一种基于Spring框架的批量文件上传方法,通过修改前端页面和控制器类,实现了多文件的同时上传。文章详细展示了如何在form中添加多个文件输入字段,并在后端使用CommonsMultipartFile数组接收和处理上传的文件。

一.思路

  在文件上传的基础上引入数组可以实现批量上传,只需要更改一下前段页面和controller类即可

  文件上传: https://www.cnblogs.com/aihuadung/p/10167507.html

二.实现

  在文件上传的基础上更改fileupload.jsp

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

  

  创建HelloController类

package com.ahd.controller;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

import javax.servlet.http.HttpServletRequest;

import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.commons.CommonsMultipartFile;

@Controller
public class HelloController5{
    @RequestMapping("/batchupload")
    public String upload(@RequestParam("file")CommonsMultipartFile []files,HttpServletRequest req,ModelMap mm) throws IOException{
        //获取上传路径
        String path=req.getRealPath("upload");
        
        InputStream is=null;
        OutputStream os=null;
        
        for(CommonsMultipartFile file:files){
            //获取文件名称
            String filename=file.getOriginalFilename();
            
            is = file.getInputStream();
            os = new FileOutputStream(new File(path,filename));
            
            byte[]b=new byte[1024];
            int len=0;
            
            while((len=is.read(b))!=-1){
                os.write(b, 0, len);
            }
        }
        
        is.close();
        os.close();
        
        mm.addAttribute("msg", "文件上传成功");
        return "success";
    }
}

 

转载于:https://www.cnblogs.com/aihuadung/p/10167773.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值