Spring获取表单传输的所有数据,包括所有文本字段和所有文件字段

Posted by youthred on July 17, 2021
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
package net.add1s.util;

import cn.hutool.core.io.resource.WebAppResource;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.apache.commons.io.IOUtils;
import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.FileOutputStream;
import java.util.*;

/**
 * @author github.com@lalafaye
 */
public class UploadUtils {

    /**
     * 所有文本字段
     */
    public static final String TEXT_FIELDS = "text_fields";

    /**
     * 所有文件字段
     */
    public static final String FILE_FIELDS = "file_fields";

    /**
     * 上传大小限制(2M)
     */
    private static long maxUploadSize = 2097152;

    /**
     * 文件保存目录路径
     */
    private static String savePath = "";

    /**
     * 文件上传保存文件夹名
     */
    private static String basePath = "upload";

    public static boolean upload(HttpServletRequest request) {
        List<FileItem> fileList = (List<FileItem>) getAllItems(request).get(FILE_FIELDS);
        System.out.println(fileList.size());
        if (fileList != null) {
            for (FileItem file : fileList) {
                saveFile(file);
            }
        }
        return false;
    }

    /**
     * 获取表单中的所有文本和文件字段
     *
     * @param request
     * @return map
     */
    public static Map getAllItems(HttpServletRequest request) {

        // savePath = new WebAppResource("\\" + basePath).toString();

        savePath = "D:\\IntelliJ_IDEA_2018_3_1\\IDEA_workspace\\Confession\\src\\main\\webapp\\upload";

        // 存储表单字段和非表单字段
        Map<String, Object> map = new HashMap<>(2);

        // 第一步:判断request
        boolean isMultipart = ServletFileUpload.isMultipartContent(request);

        // 第二步:解析request
        if (isMultipart) {
            // Create a factory for disk-based file items
            DiskFileItemFactory factory = new DiskFileItemFactory();

            // 阀值(10M),超过这个值才会写到临时目录,否则在内存中
            factory.setSizeThreshold(1024 * 1024 * 10);
            factory.setRepository(new File(savePath + "\\temp"));

            // Create a new file upload handler
            ServletFileUpload upload = new ServletFileUpload(factory);

            upload.setHeaderEncoding("UTF-8");

            // 最大上传限制
            upload.setSizeMax(maxUploadSize);

            /* FileItem */
            List<FileItem> items = null;
            // Parse the request
            try {
                items = upload.parseRequest(request);
            } catch (FileUploadException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }

            // 第3步:处理uploaded items
            if (items != null && items.size() > 0) {
                Iterator<FileItem> iter = items.iterator();
                // 文件域对象List
                List<FileItem> fileFieldsList = new ArrayList<>();
                // 表单字段Map
                Map<String, String> textFieldsMap = new HashMap<>();
                while (iter.hasNext()) {
                    FileItem item = iter.next();
                    // 处理所有表单元素和文件域表单元素
                    if (item.isFormField()) { // 表单元素
                        String name = item.getFieldName();
                        String value = item.getString();
                        textFieldsMap.put(name, value);
                    } else { // 文件域表单元素
                        fileFieldsList.add(item);
                    }
                }
                map.put(FILE_FIELDS, fileFieldsList);
                map.put(TEXT_FIELDS, textFieldsMap);
            }
        }
        return map;
    }

    public static AjaxResult saveFile(FileItem item) {

        System.out.println(savePath);

        // 文件名
        String fileName = item.getName();
        // 后缀
        String fileExt = fileName.substring(fileName.lastIndexOf(".") + 1).toLowerCase();

        // 检查文件大小
        if (item.getSize() > maxUploadSize) {
            // TODO
            return AjaxResult.me().setSuccess(false).setMsg("文件太大,上传失败");
        } else {
            String newFileName = UUID.randomUUID().toString() + "." + fileExt;
            try {
                IOUtils.copy(item.getInputStream(), new FileOutputStream(new File(savePath, newFileName)));
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        System.gc();
        return AjaxResult.me();
    }
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
package net.add1s.util;

/**
 * Ajax请求响应对象的类
 *
 * @author github.com@lalafaye
 */
public class AjaxResult {

    private boolean success = true;

    private String msg = "Successful operation!";

    /**
     * 返回到前台对象
     */
    private Object resultObj;

    public boolean isSuccess() {
        return success;
    }

    public AjaxResult setSuccess(boolean success) {
        this.success = success;
        return this;
    }

    public String getMsg() {
        return msg;
    }

    public AjaxResult setMsg(String msg) {
        this.msg = msg;
        return this;
    }

    public Object getResultObj() {
        return resultObj;
    }

    public AjaxResult setResultObj(Object resultObj) {
        this.resultObj = resultObj;
        return this;
    }

    /**
     * AjaxResult.me() 成功
     * AjaxResult.me().setMsg() 成功
     * AjaxResult.me().setSuccess(false).setMsg("失败");
     *
     * @return
     */
    public static AjaxResult me() {
        return new AjaxResult();
    }
}