1. 程式人生 > >2018 SpringMVC 單多檔案上傳

2018 SpringMVC 單多檔案上傳

一、pom.xml

<!--引用springMVC依賴-->
<dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-webmvc</artifactId>
    <version>5.1.0.RELEASE</version>
</dependency>

<!--引用上傳與下載依賴-->
<dependency>
    <groupId>commons-fileupload</groupId>
    <artifactId>commons-fileupload</artifactId>
    <version>1.3.3</version>
</dependency>

二、springmvc-config.xml

<!-- 檔案上傳配置,這裡id的名稱固定寫法 -->
<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver"></bean>

三、FileController.java

package cn.kaxlm6.mybatis.controller;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.util.FileCopyUtils;
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.MultipartFile;

import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.util.Calendar;

/**
 * Created by IntelliJ IDEA.
 *
 * @author xlm
 * description:
 * path: mybatisProject-cn.kaxlm6.mybatis.controller-FileController
 * date: 2018/10/19 16:48
 * version: 02.06
 * To change this template use File | Settings | File Templates.
 */
@Controller
public class FileController {

    Logger logger = LogManager.getLogger();

    @Autowired
    ServletContext context;

    @RequestMapping(value = "/fileUpload", method = RequestMethod.POST)
    public void fileUpload(@RequestParam("uploadFile") MultipartFile[] file, HttpServletRequest request) throws Exception {

        for (int i = 0; i < file.length; i++) {

            //判斷檔案是否為空
            if (!file[i].isEmpty()) {

                //獲得原檔名
                String fileName = file[i].getOriginalFilename();
                //File.separator表示在 UNIX 系統上,此欄位的值為 /;在 Windows 系統上,它為 \,如:C:\tmp\test.txt和tmp/test.txt
                String filePath = context.getRealPath("") + "upload" + File.separator;

                //獲得當前日期
                Calendar ca = Calendar.getInstance();
                //拼接日期資料夾
                filePath += ("" + ca.get(Calendar.YEAR) + (ca.get(Calendar.MONTH) + 1) + ca.get(Calendar.DATE));
                File dateDir = new File(filePath);

                //判斷當前日期資料夾是否存在,不存在建立
                if (!dateDir.exists()) {
                    dateDir.mkdirs();
                }

                //檔名由客戶端IP地址+系統當前毫秒陣列成
                filePath += File.separator + request.getRemoteAddr().replace(":", "") + System.currentTimeMillis() + fileName.substring(fileName.lastIndexOf("."));

                // 複製本地檔案到伺服器
                FileCopyUtils.copy(file[i].getBytes(), new File(filePath));

            } else {

                logger.info("檔案上傳異常");

            }

        }

    }

}

四、index.jsp

<%--
  Created by IntelliJ IDEA.
  User: xlm
  Date: 2018/9/29
  Time: 9:22
  To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" %>

<html>
<head>
    <title>Title</title>
</head>

<body>

    <form action="/fileUpload.xlm" method="post" enctype="multipart/form-data">
        <input type="file" name="uploadFile" />
        <input type="file" name="uploadFile" />
        <input type="submit" value="提交">
    </form>

</body>

</html>