from 表单上传多个文件?

和单个上传文件基本相同,就是需要在后台控制器中,用数组来接收 jsp页面提交过来的file数据。

也分为三个部分演示。

一、jsp

  

<%--
  Created by IntelliJ IDEA.
  User: Administrator
  Date: 2019/8/12
  Time: 14:32
  To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>多文件上传</title>
</head>
<%--  多文件上传  jsp 部分
      1.在form  标签中定义属性     enctype="multipart/form-data"
      2.在上传的input中定义属性    multiple="multiple"


--%>
<body>
    <form action="../test" method="post" enctype="multipart/form-data">
            <div>上传文件:<input type="file" name="file" multiple="multiple"></div>
            <div> <input type="submit" value="上传" /> </div>
    </form>
</body>
</html>

 

二、后台控制器

package com.aaa.controller;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;
import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
/*
*
* 多文件上传  1.jsp   2.后台控制层
*
* 将接受的 file 属性  定义成一个数组
* [email protected]("file")MultipartFile [] files
*
* 2.2  通过for循环  将得到的结果 便利出来。
* */

@Controller
public class TestController {
    @RequestMapping("/test")
    public String test(@RequestParam("file")MultipartFile [] files,Model model,HttpServletRequest request) throws IOException {

        for (MultipartFile file:files
             ) {

            if (!file.isEmpty()){
                //获得上传的目标位置
                String path = request.getSession().getServletContext().getRealPath("/static/upload");

                //目标文件的对象
                String fileName = file.getOriginalFilename();

                File file1 = new File(path + "/" + fileName);

                //父级目录  不在  就创建一个
                if (!file1.getParentFile().exists()){
                    file1.mkdirs();
                }

                //数据库没有的文件  才上传
                if (!file1.exists()){
                    file.transferTo(file1);
                    model.addAttribute("file",fileName);
                }
            }else {
                model.addAttribute("file","上传文件为空");
            }
        }
        return  "view/ok1";
    }
}

 

三、接收数据的jsp页面。

<%--
  Created by IntelliJ IDEA.
  User: Administrator
  Date: 2019/8/12
  Time: 14:45
  To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>接收数据</title>
</head>
<body>
    上传的文件:${file}
</body>
</html>

相关文章

HTML代码中要想改变字体颜色,常常需要使用CSS样式表。CSS是...
HTML代码如何让字体盖住图片呢?需要使用CSS的position属性及...
HTML代码字体设置 在HTML中,我们可以使用标签来设置网页中的...
在网页设计中,HTML代码的字体和字号选择是非常重要的一个环...
HTML(Hypertext Markup Language,超文本标记语言)是一种用...
外链是指在一个网页中添加一个指向其他网站的链接,用户可以...