欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

jquery/js 用ajax上传xml文件并解析返回数据展示的实例

程序员文章站 2022-03-27 23:24:00
利用ajax上传文件,自定义数据处理方法前段时间做了个页面需要上传文件到后台,并解析后返回解析数据在前台预览,细节部分处理了好久,搞定后决定分享一波经验。我并没有用form表单的submit提交,虽然也可行,但是对于返回数据的处理总有些细节不到位,还是用ajax一步到位,话不多说,上代码:前端代码html页面

利用ajax上传文件,自定义数据处理方法

前段时间做了个页面需要上传文件到后台,并解析后返回解析数据在前台预览,细节部分处理了好久,搞定后决定分享一波经验。

我并没有用form表单的submit提交,虽然也可行,但是对于返回数据的处理总有些细节不到位,还是用ajax一步到位,话不多说,上代码:

前端代码

html页面

<html lang="en">
<head>
    <meta http-equiv="Content-Type" content="multipart/form-data;charset=utf-8"/>
    <title>通道配置上传</title>
    <script type="text/javascript" src="app/javascript/lib/jquery-3.4.1/jquery.js"></script>
    <script type="text/javascript" src="app/javascript/lib/jquery/jquery.form.js"></script>
    <script type="text/javascript" src="app/javascript/orientjs/jqueryjs/webConfig/channelInit.js"></script>
    <link rel="stylesheet" type="text/css" href="app/styles/webConfig/channelStyle.css">
</head>
<body>
<div class="one">
    <form class="two" id="uploadForm" method="post" enctype="multipart/form-data" name = "uploadFormName">
    <input type="file" id="file_upload" name="upload" value="选择上传文件">
        <button id="look" type="button" onclick="outLook()">预览</button>
    </form>
    <div class="three">
    <button id="sure" type="button" onclick="toSendData()">确定</button>
    </div>
    <div class="four">
        <table id="dataTable" border="1">
            <thead>
            <tr>
                <th width="200">IP</th>
                <th width="200">Param</th>
            </tr>
            </thead>
            <tbody>
            </tbody>
        </table>
    </div>
</div>
</body>
</html>

主要的js方法

function outLook() {
    if (document.getElementById("file_upload").value == null || document.getElementById("file_upload").value == "") {
        confirm("请选择文件进行预览");
    } else {
        //document.getElementById("uploadForm").action = "channelConfig/outLookData.rdm";
        //document.getElementById("uploadForm").submit();
        var uploadfile = $('#file_upload')[0].files[0];
        var formData = new FormData();
        formData.append("upload",uploadfile);
        //区分预览和发送功能
        formData.append("todo","1");
        $.ajax({
            url: "channelConfig/outLookData.rdm",
            type: "POST",
            dataType: "json",
            data:formData,
            processData: false,
            contentType:false,
            success: function (data) {
                alert(data.msg);
                if (data.msg=="解析成功") {
                    var obj = eval(data.results);
                    var tbody =$('<tbody></tbody>');
                    $(obj).each(function (index) {
                        var val = obj[index];
                        var tr = $('<tr></tr>');
                        tr.append('<td>'+val.IP+'</td>'+'<td>'+val.Param+'</td>')
                        tbody.append(tr);
                    });
                    $('#dataTable tbody').replaceWith(tbody);
                }
            },
            error: function () {
                alert("预览失败");
            }
        })
    }
}

function toSendData() {
    if (document.getElementById("file_upload").value == null || document.getElementById("file_upload").value == "") {
        confirm("请先选择文件");
    } else {
         //document.getElementById("uploadForm").action = "channelConfig/toSendData.rdm";
         //document.getElementById("uploadForm").submit();
        var uploadfile = $('#file_upload')[0].files[0];
        var formData = new FormData();
        formData.append("upload",uploadfile);
        //区分预览和发送功能
        formData.append("todo","2");
        $.ajax({
            url: "channelConfig/toSendData.rdm",
            type: "POST",
            dataType: "json",
            data:formData,
            processData: false,
            contentType:false,
            success: function (data) {
                alert(data.msg + " sendText: " + eval(data.results)[0].all);
            },
            error: function () {
                alert("发送失败");
            }
        })
    }
}

其中最重要的有两点:
1.form标签中的enctype="multipart/form-data"一定要加上;
2.js中ajax方法contentType:false属性要标明,不然后台会报错

后台代码

@RequestMapping(value = "outLookData",method = RequestMethod.POST)
@ResponseBody
public ExtGridData<Map<String,String>> outLookData(@RequestParam("upload") MultipartFile file,@RequestParam("todo") String todo, HttpServletRequest request) throws IOException {
        ExtGridData<Map<String,String>> retVal = new ExtGridData<>();
        ServletContext servletContext = request.getSession().getServletContext();
        String sourceName = file.getOriginalFilename();//原文件名
        try {
            String fileType = sourceName.substring(sourceName.lastIndexOf("."));
            //判断文件内容为空
            if (file.isEmpty() || StringUtils.isBlank(fileType)) {
                retVal.setSuccess(false);
                retVal.setMsg("选择文件内容为空");
                return retVal;
            }
            //判断文件格式
            if (!".xml".equals(fileType.toLowerCase())) {
                retVal.setSuccess(false);
                retVal.setMsg("选择文件格式错误");
                return retVal;
            }
            //存放文件临时路径
            String base = servletContext.getRealPath("/app/upload/");
            File temporaryFile = new File(base);
            if (!temporaryFile.exists()) {
                temporaryFile.mkdirs();
            }
            //将文件上传到临时目录
            UUID uuid = UUID.randomUUID();
            String path = base + File.separator + uuid + sourceName;
            File upload = new File(path);
            List<Map<String,String>> list;
            List<Map<String,String>> relList;
            try {
                file.transferTo(upload);
                //解析文件并返回解析数据
                list = FileReaderXml(path);
                if (todo.equals("1")) {
                    if (list.size() >= 9) {
                        relList = list.subList(0,8);
                    }else {
                        list.remove(list.size()-1);
                        relList = list;
                    }
                    retVal.setResults(relList);
                }else {
                    retVal.setResults(list);
                }
                retVal.setMsg("解析成功");
                retVal.setSuccess(true);
            } catch (DocumentException | NullPointerException e) {
                retVal.setSuccess(false);
                retVal.setMsg("文件内容格式错误,解析失败");
                e.printStackTrace();
            }
            upload.delete();
        }catch (StringIndexOutOfBoundsException e) {
            retVal.setSuccess(false);
            retVal.setMsg("选择文件格式错误");
            return retVal;
        }
        return retVal;
    }

解析xml的方法也附上,我这里是格式化的xml文件,大家可以根据自己需要解析的文件格式自定义

private List<Map<String,String>> FileReaderXml(String filename) throws DocumentException,NullPointerException{
        List<Map<String, String>> list = new ArrayList<>();
        Map<String, String> map;
        SAXReader reader = new SAXReader();
        Document document = reader.read(new File(filename));
        Element root = document.getRootElement();
        Element node = root.element("ClientsDataInfo");
        Element oneElement = node.element("NetDataUDPForwardingTargets");
        Element twoElement = oneElement.element("UDPTargetInfo");
        Iterator it = twoElement.elementIterator();
        String param = "";
        while (it.hasNext()) {
            Element threeElement = (Element) it.next();
            if (threeElement.attribute("SendAll").getValue().equals("True")) {
                String sendIP = threeElement.attribute("IP").getValue();
                Iterator iterator = node.elementIterator();
                while (iterator.hasNext()) {
                    Element fourElement = (Element) iterator.next();
                    if (fourElement.getName().equals("Client") && fourElement.attribute("IP").getValue().equals(sendIP)) {
                        List<Element> elementsList = fourElement.elements("Param");
                        for (Element e: elementsList) {
                            map = new HashMap<>();
                            map.put("IP",sendIP);
                            map.put("Param",e.getText());
                            list.add(map);
                            if (param.equals("")) {
                                param = e.getText();
                            }else {
                                param = param + "," + e.getText();
                            }
                        }
                    }
                }
            }
        }
        Map<String, String> allParam = new HashMap<>();
        allParam.put("all",param);
        list.add(allParam);
        return list;
    }

前台显示效果:

jquery/js 用ajax上传xml文件并解析返回数据展示的实例

本文地址:https://blog.csdn.net/weixin_44829395/article/details/107383985

相关标签: 技术分享 java