我是靠谱客的博主 无奈航空,这篇文章主要介绍Springboot-前端文件上传xml后端完成解析前端代码后端效果,现在分享给大家,希望可以做个参考。

前端代码

复制代码
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
<@html title="上传文件" import="layui,sign"> <div class="layui-upload"> <button type="button" class="layui-btn layui-btn-normal" id="testList">选择文件 </button> <div class="layui-upload-list"> <table class="layui-table"> <thead> <tr> <th>文件名</th> <th>大小</th> <th>状态</th> <th>路径</th> <th>操作</th> </tr> </thead> <tbody id="demoList"></tbody> </table> </div> <button type="button" class="layui-btn" id="testListAction">开始上传</button> </div> <script> let files=[]; layui.use('upload', function(){ let $ = layui.jquery ,upload = layui.upload; //多文件列表示例 let demoListView = $('#demoList') ,uploadListIns = upload.render({ elem: '#testList', url: '${base}/demo/uploadXmlFiles', // 限制文件大小,单位 KB // size: 60, accept: 'file', //只允许上传文本文件 exts: 'xml', // 可放扩展数据 key-value // data:{'ID':277}, multiple: true, auto: false, bindAction: '#testListAction', choose: function(obj){ let files = this.files = obj.pushFile(); //将每次选择的文件追加到文件队列 //读取本地文件 obj.preview(function(index, file, result){ let tr = $(['<tr id="upload-'+ index +'">' ,'<td>'+ file.name +'</td>' ,'<td>'+ (file.size/1014).toFixed(1) +'kb</td>' ,'<td>等待上传</td>' ,'<td></td>' ,'<td>' ,'<button class="layui-btn layui-btn-mini demo-reload layui-hide">重传</button>' ,'<button class="layui-btn layui-btn-mini layui-btn-danger demo-delete">删除</button>' ,'</td>' ,'</tr>'].join('')); //单个重传 tr.find('.demo-reload').on('click', function(){ obj.upload(index, file); }); //删除 tr.find('.demo-delete').on('click', function(){ delete files[index]; //删除对应的文件 tr.remove(); uploadListIns.config.elem.next()[0].value = ''; //清空 input file 值,以免删除后出现同名文件不可选 }); demoListView.append(tr); }); }, done: function(res, index, upload){ console.log(res); // 上传成功 if(res.code === 0){ files.push({"fileName":res.fileName,"fileUrl":res.fileUrl,"fileSize":res.fileSize}); let json = JSON.stringify(files); //将上传的文件信息加入到集合中并转换成json字符串 $("#fileJson").attr("value", json); let fileUrl=res.fileUrl; let tr = demoListView.find('tr#upload-'+ index), tds = tr.children(); tds.eq(2).html('<span style="color: #5FB878;">上传成功</span>'); tds.eq(3).html('<span>'+fileUrl+'</span>'); //清空操作 tds.eq(4).html(''); //删除文件队列已经上传成功的文件 return delete this.files[index]; } this.error(index, upload); } }); }); </script> </@html>

图像为:
在这里插入图片描述

后端

复制代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
@PostMapping("/uploadXmlFiles") @ResponseBody public Object uploadXmlFiles(MultipartFile file, HttpServletRequest request) throws JSONException{ File xmlFile = FileUtil.getFileByMvc(file, request, "xml"); try{ if(xmlFile.exists()){ SAXReader saxReader = new SAXReader(); // 从文件流读入xml数据 Document document = saxReader.read(xmlFile); String json = XmlUtil.xmlToJson(document.getRootElement()); String savePath = "D:\Files\Tmp\test.xml"; Document xmlDocument = XmlUtil.jsonToXml(json); XmlUtil.writeXml(xmlDocument, savePath, "gb2312"); return success(); } }catch (Exception e){ e.printStackTrace(); } return fail(); }

自己封装了一个工具类

复制代码
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
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
import com.alibaba.fastjson.JSON; import com.alibaba.fastjson.JSONArray; import com.alibaba.fastjson.JSONObject; import com.alibaba.fastjson.serializer.SerializerFeature; import org.dom4j.Attribute; import org.dom4j.Document; import org.dom4j.DocumentHelper; import org.dom4j.Element; import org.dom4j.io.OutputFormat; import org.dom4j.io.XMLWriter; import java.io.*; import java.util.List; /** * xml工具类 * @author XmlUtil * @date 2022/06/17 */ public class XmlUtil { /**将xml转换为json * @param root xml根节点 * @return json字符串 */ public static String xmlToJson(Element root){ JSONObject jsonObject = xmlToJsonObject(root); String json = JSON.toJSONString(jsonObject, SerializerFeature.PrettyFormat, SerializerFeature.WriteMapNullValue, SerializerFeature.WriteDateUseDateFormat); return json; } /**构建json对象,将根节点下的解析后的数据放在根节点下 * @param element 文档的根节点. * @return json对象 */ public static JSONObject xmlToJsonObject(Element element){ JSONObject supJson = new JSONObject(); JSONObject json = new JSONObject(); dom4j2Json(element, json); supJson.put(element.getName(), json); return supJson; } /**解析当前节点下的所有内容并放入JSONObject中 * @param element 节点 * @param json 需要放入的jsonObject */ private static void dom4j2Json(Element element, JSONObject json) { // 如果是属性 for (Object o : element.attributes()) { Attribute attr = (Attribute) o; if (!isEmpty(attr.getValue())) { json.put("-" + attr.getName(), attr.getValue()); } } List<Element> chdEl = element.elements(); // 如果没有子元素,只有一个值 if (chdEl.isEmpty() && !isEmpty(element.getText())) { json.put(element.getName(), element.getText()); } // 有子元素 for (Element e : chdEl) { // 子元素也有子元素 if (!e.elements().isEmpty()) { JSONObject chdjson = new JSONObject(); dom4j2Json(e, chdjson); Object o = json.get(e.getName()); if (o != null) { JSONArray jsona = null; // 如果此元素已存在,则转为jsonArray if (o instanceof JSONObject) { JSONObject jsono = (JSONObject)o; json.remove(e.getName()); jsona = new JSONArray(); jsona.add(jsono); jsona.add(chdjson); } if (o instanceof JSONArray) { jsona = (JSONArray)o; jsona.add(chdjson); } json.put(e.getName(), jsona); } else { if (!chdjson.isEmpty()) { json.put(e.getName(), chdjson); } } } else { // 子元素没有子元素 for (Object o : element.attributes()) { Attribute attr = (Attribute)o; if (!isEmpty(attr.getValue())) { json.put("-" + attr.getName(), attr.getValue()); } } if (!e.getText().isEmpty()) { json.put(e.getName(), e.getText()); } // 最后一层且有属性 if (e.getText().isEmpty() && !e.attributes().isEmpty()) { Object oe = json.get(e.getName()); if (oe == null) { JSONObject jsonObject = new JSONObject(); for (Object o : e.attributes()) { Attribute attr = (Attribute) o; jsonObject.put("-" + attr.getName(), attr.getValue()); } json.put(e.getName(), jsonObject); } else { JSONArray jsonArray = new JSONArray(); if (oe instanceof JSONObject) { JSONObject oeJsonObject = (JSONObject)oe; jsonArray.add(oeJsonObject); } if (oe instanceof JSONArray) { jsonArray = (JSONArray) oe; } JSONObject jsonObject = new JSONObject(); for (Object o : e.attributes()) { Attribute attr = (Attribute) o; if (!isEmpty(attr.getValue())) { jsonObject.put("-" + attr.getName(), attr.getValue()); } } jsonArray.add(jsonObject); json.put(e.getName(), jsonArray); } } } } } /**判断字符串是否为空 * @param value 字符串 * @return 布尔 */ private static boolean isEmpty(String value) { return value == null || value.length() == 0 || "null".equals(value); } /**将xml内容写入本地 * @param document xml * @param path 存储路径 * @param format xml格式 * @return 布尔 */ public static boolean writeXml(Document document, String path, String format){ File file = new File(path); OutputFormat of = OutputFormat.createPrettyPrint(); // 设置编码格式 of.setEncoding(format); try { XMLWriter writer = new XMLWriter(new FileOutputStream(file), of); writer.write(document); writer.close(); return true; } catch (IOException e) { e.printStackTrace(); } return false; } /**json字符串转换成xml字符串 * @param jsonStr json字符串 * @return xml */ public static Document jsonToXml(String jsonStr){ JSONObject json = JSON.parseObject(jsonStr); Document document = DocumentHelper.createDocument(); // root对象只能有一个 for (String rootKey : json.keySet()) { Element root = jsonToElement(json.getJSONObject(rootKey), rootKey); document.add(root); break; } return document; } /** * @param json json对象 * @param nodeName 根节点名称 * @return xml结构 */ private static Element jsonToElement(JSONObject json, String nodeName) { Element node = DocumentHelper.createElement(nodeName); for (String key : json.keySet()) { //当前key是属性 if(key.charAt(0) == '-'){ String k = key.substring(1, key.length()); String value = json.get(key).toString(); node.addAttribute(k, value); }else{ Object child = json.get(key); if (child instanceof JSONObject) { node.add(jsonToElement(json.getJSONObject(key), key)); }else { JSONArray childs = (JSONArray) child; for (int i = 0; i < childs.size(); i++) { JSONObject jsonObject = (JSONObject) childs.get(i); node.add(jsonToElement(jsonObject, key)); } } } } return node; } }

效果

文件初始内容:

复制代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
<?xml version="1.0" encoding="gb2312"?> <REPORT TableCount="3"> <DATA DATANAME="1" COMMENTS="1"> <Row XMID="abc" XH="qwe"/> </DATA> <DATA DATANAME="2" COMMENTS="2"> <Row XMID="abc" XH="qwe"/> </DATA> <DATA DATANAME="3" COMMENTS="3"> <Row XMID="abc" XH="qwe"/> </DATA> <DATA DATANAME="4" COMMENTS="4"> <Row XMID="abc" XH="qwe"/> </DATA> </REPORT>

xml转json

复制代码
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
{ "REPORT":{ "-TableCount":"3", "DATA":[ { "-COMMENTS":"1", "-DATANAME":"1", "Row":{ "-XH":"qwe", "-XMID":"abc" } }, { "-COMMENTS":"2", "-DATANAME":"2", "Row":{ "-XH":"qwe", "-XMID":"abc" } }, { "-COMMENTS":"3", "-DATANAME":"3", "Row":{ "-XH":"qwe", "-XMID":"abc" } }, { "-COMMENTS":"4", "-DATANAME":"4", "Row":{ "-XH":"qwe", "-XMID":"abc" } } ] } }

json转xml:

复制代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
<?xml version="1.0" encoding="gb2312"?> <REPORT TableCount="3"> <DATA COMMENTS="1" DATANAME="1"> <Row XH="qwe" XMID="abc"/> </DATA> <DATA COMMENTS="2" DATANAME="2"> <Row XH="qwe" XMID="abc"/> </DATA> <DATA COMMENTS="3" DATANAME="3"> <Row XH="qwe" XMID="abc"/> </DATA> <DATA COMMENTS="4" DATANAME="4"> <Row XH="qwe" XMID="abc"/> </DATA> </REPORT>

最后

以上就是无奈航空最近收集整理的关于Springboot-前端文件上传xml后端完成解析前端代码后端效果的全部内容,更多相关Springboot-前端文件上传xml后端完成解析前端代码后端效果内容请搜索靠谱客的其他文章。

本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
点赞(92)

评论列表共有 0 条评论

立即
投稿
返回
顶部