天天看點

Java,SpringBoot,MultipartFile,表單處理上傳/檔案上傳,代碼

作者:IT小奮鬥

背景

SpringBoot,2.3.9.RELEASE,表單上傳檔案,案例代碼。

案例

背景代碼

package com.what21.demo.controller;

import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;

@Controller
@RequestMapping("/upload")
@Slf4j
public class FileUploadController {

    @RequestMapping(value = "/show", method = {RequestMethod.GET, RequestMethod.POST})
    @ResponseBody
    public Object show(HttpServletRequest request) {
        Map<String, Object> dataMap = new HashMap<>();
        dataMap.put("code", "ok");
        dataMap.put("status", "success");
        return dataMap;
    }

    @RequestMapping(value = "/multiUpload", method = {RequestMethod.GET, RequestMethod.POST})
    @ResponseBody
    public Object multiUpload(HttpServletRequest request) {
        Map<String, Object> dataMap = new HashMap<>();
        dataMap.put("code", "ok");
        // ===================================================================================//
        // ===== 解析參數&儲存檔案
        // ===================================================================================//
        String storagePath = "D:/Temp/Upload/";
        // 多檔案
        MultipartHttpServletRequest multipartHttpRequest = (MultipartHttpServletRequest) request;
        Map<String, MultipartFile> multipartFileMap = multipartHttpRequest.getFileMap();
        Set<String> keySet = multipartFileMap.keySet();
        for (String key : keySet) {
            MultipartFile multipartFile = multipartFileMap.get(key);
            if (multipartFile.isEmpty()) {
                continue;
            }
            String fileName = multipartFile.getOriginalFilename();
            try {
                File dest = new File(storagePath + fileName);
                multipartFile.transferTo(dest);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        // ===================================================================================//
        // ===== 傳回結果
        // ===================================================================================//
        return dataMap;
    }

    @RequestMapping(value = "/multiUpload2", method = {RequestMethod.GET, RequestMethod.POST})
    @ResponseBody
    public Object multiUpload2(HttpServletRequest request) {
        Map<String, Object> dataMap = new HashMap<>();
        dataMap.put("code", "ok");
        // ===================================================================================//
        // ===== 解析參數&儲存檔案
        // ===================================================================================//
        String storagePath = "D:/Temp/Upload/";
        // 多檔案
        MultipartHttpServletRequest multipartHttpRequest = (MultipartHttpServletRequest) request;
        List<MultipartFile> multipartFileList = multipartHttpRequest.getFiles("files");
        String filePath = storagePath;
        for (int i = 0; i < multipartFileList.size(); i++) {
            MultipartFile file = multipartFileList.get(i);
            if (file.isEmpty()) {
                continue;
            }
            String fileName = file.getOriginalFilename();
            File dest = new File(filePath + fileName);
            try {
                file.transferTo(dest);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        // ===================================================================================//
        // ===== 傳回結果
        // ===================================================================================//
        return dataMap;
    }

}           

配置類:

/**
 * 允許不規範 URL 通路
 * @return
 */
@Bean
public HttpFirewall httpFirewall() {
    return new DefaultHttpFirewall();
}           

前端代碼:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Form表單上傳</title>
    <script src="https://cdn.bootcdn.net/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
    <link href="https://cdn.bootcdn.net/ajax/libs/twitter-bootstrap/4.6.1/css/bootstrap.min.css" rel="stylesheet">
</head>
<body>
    <div class="container " style="width:600px;">
        <span>
          <h1>Form表單上傳</h1>
        </span>
        <form method="post" action="http://localhost:8001/demo02/upload/multiUpload" enctype="multipart/form-data">
            <input type="hidden" name="model" value="object" />
            <div class="form-group">
                <label for="address">上傳位址:</label>
                <input id="address" name="address" class="form-control" value="http://localhost:8001/demo02/upload/multiUpload" />
            </div>
            <div class="form-group">
                <label for="modular">一級子產品:</label>
                <input id="modular" name="modular" class="form-control" value="modular"/>
            </div>
            <div class="form-group">
                <label for="model">二級子產品:</label>
                <input id="model" name="model" class="form-control" value="model" />
            </div>
            <div class="form-group">
                <label for="file1">上傳檔案1:</label>
                <input id="file1" type="file" name="file" value="" class="form-control" />
            </div>
            <div class="form-group">
                <label for="file2">上傳檔案2:</label>
                <input id="file2" type="file" name="file2" value="" class="form-control" />
            </div>
            <div class="form-group">
                <label for="desc">描述:</label>
                <textarea id="desc" name="desc" class="form-control" style="min-height: 200px;"></textarea>
            </div>
            <div class="form-group form-check">
                <label class="form-check-label">
                    <input class="form-check-input" type="checkbox">記住我
                </label>
            </div>
            <button type="reset" class="btn btn-secondary">取消</button>
            <button type="submit" class="btn btn-danger">送出</button>
        </form>
    </div>
</body>
</html>
           
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Form表單上傳</title>
    <script src="https://cdn.bootcdn.net/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
    <link href="https://cdn.bootcdn.net/ajax/libs/twitter-bootstrap/4.6.1/css/bootstrap.min.css" rel="stylesheet">
</head>
<body>
    <div class="container " style="width:600px;">
        <span>
          <h1>Form表單上傳</h1>
        </span>
        <form method="post" action="http://localhost:8001/demo02/upload/multiUpload2" enctype="multipart/form-data">
            <input type="hidden" name="model" value="object" />
            <div class="form-group">
                <label for="address">上傳位址:</label>
                <input id="address" name="address" class="form-control" value="http://localhost:8001/demo02/upload/multiUpload2" />
            </div>
            <div class="form-group">
                <label for="modular">一級子產品:</label>
                <input id="modular" name="modular" class="form-control" value="modular"/>
            </div>
            <div class="form-group">
                <label for="model">二級子產品:</label>
                <input id="model" name="model" class="form-control" value="model" />
            </div>
            <div class="form-group">
                <label for="file1">上傳檔案1:</label>
                <input id="file1" type="file" name="file" value="" class="form-control" />
            </div>
			<div class="form-group">
                <label for="file2">上傳檔案2:</label>
                <input id="file2" type="file" name="file" value="" class="form-control" />
            </div>
            <div class="form-group">
                <label for="desc">描述:</label>
                <textarea id="desc" name="desc" class="form-control" style="min-height: 200px;"></textarea>
            </div>
            <div class="form-group form-check">
                <label class="form-check-label">
                    <input class="form-check-input" type="checkbox">記住我
                </label>
            </div>
            <button type="reset" class="btn btn-secondary">取消</button>
            <button type="submit" class="btn btn-danger">送出</button>
        </form>
    </div>
</body>
</html>