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 屬性  定義成一個數組
* 2.1@RequestParam("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>

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM