文件上传(多文件)

Spring MVC 方式上传

1. 添加maven依赖

 <!-- 文件上传依赖 -->
<dependency>
    <groupId>commons-fileupload</groupId>
    <artifactId>commons-fileupload</artifactId>
    <version>1.3.3</version>
</dependency>

用 maven 添加依赖会自动依赖commons-io-2.2.jar 手动导包需注意


2. 配置 spring xml文件

 <!--文件下载-->
<bean class="org.springframework.web.multipart.commons.CommonsMultipartResolver" id="multipartResolver">
    <!--字符集-->
    <property name="defaultEncoding" value="UTF-8"/>
    <!--最大上传大小 单位字节-->
    <property name="maxUploadSize" value="1024000"/>
</bean>

bean中的id属性必须给出,否则报: Required String parameter 'xxx' is not present异常


3. 表单页面

<form action="/fileUpload" method="post" enctype="multipart/form-data">
    File : <input type="file" name="file"> <br>
    DESC : <input type="text" name="desc"> <br>
    <input type="submit">
</form>

4. Controller 类


    //    文件上传
    @RequestMapping("/fileUpload")
    public ModelAndView fileUpload(@RequestParam("desc") String desc,
                                   @RequestParam("file") MultipartFile file, HttpSession session) throws IOException {
        InputStream in = file.getInputStream();
        String rootPath = session.getServletContext().getRealPath("/");
        System.out.println(rootPath);
        String path = rootPath + "/files/" + file.getOriginalFilename();
        File saveFile = new File(path);
        if (!saveFile.getParentFile().exists()) {
            if (!saveFile.getParentFile().mkdirs()) {
                throw new RuntimeException("创建文件夹失败");
            }
        }
//        System.out.println(saveFile.getPath());
        // io 操作
        FileOutputStream fos = new FileOutputStream(saveFile);
        int len = 0;
        byte[] bytes = new byte[1024];

        while ((len = in.read(bytes)) != -1) {
            fos.write(bytes, 0, len);
        }
        in.close();
        fos.close();
        //视图
        String viewName = "success";
        ModelAndView modelAndView = new ModelAndView(viewName);
        modelAndView.addObject("size", file.getSize());
        modelAndView.addObject("contentType", file.getContentType());
        modelAndView.addObject("name", file.getName());
        modelAndView.addObject("originalFilename", file.getOriginalFilename());
        modelAndView.addObject("isEmpty", file.isEmpty());
        return modelAndView;
    }

5. 多文件上传

只需在入参时用数组接收即可.用循环输出流.


   @RequestMapping("/fileUpload2")
    public String fileUpload(@RequestParam("desc") String[] desc,
                             @RequestParam("file") MultipartFile[] file) {

        for (int i = 0; i < file.length; i++) {
            System.out.println(file[i].getOriginalFilename());
        }
        return "success";
    }


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值