Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
72 views
in Technique[技术] by (71.8m points)

javascript - How to get url from networth

I'm trying to save a PDF file with spring and ajax. The request was send and received but it stuck in networth. How I get that url or save my file (in red circle). I'm using Spring boot,javascript,jquery with ajax .If you have a better way to save it please let me know.

@RequestMapping(value = "/secure/configPDF/export.jspa",method = RequestMethod.GET)
    public void exportPDF(HttpServletRequest req, HttpServletResponse resp, Model model) throws ServletException, IOException {
        String html = req.getParameter("html");
        String json = req.getParameter("json");
        InputStream inputStream = null;
        OutputStream outputStream = null;
        Object[] res= new Object[2];
        File file =null;
        File dir = null;
        String idString = String.valueOf(req.getParameter("id"));
        String errors="";
        long id = 0;
        if (idString.isEmpty() != true || idString.equalsIgnoreCase("") != true) {
            id = Long.parseLong(idString);
        }
        try{
            JSONObject jsonObject = new JSONObject(json);
        }catch (JSONException sd){
            //errors+=sd.toString();
        }
        String type = req.getParameter("type");
        ApplicationUser user = authenticationContext.getUser();
        try {
            if (StringUtils.isBlank(type)) {
                type = TYPE_PHASE;
            }
            res = pDFPrintHelper.createPDF(id, html,json);
            file = (File) res[0];
            if (res[1] != null) {
                errors+= res[1];
            }

            if (StringUtils.isNotBlank(errors)) {
                resp.sendError(500, errors);
            }
            model.addAttribute("errors",errors);
            dir = pDFPrintHelper.getTemplateDir(type, id);
            inputStream = new FileInputStream(file);
            byte[] bytes = IOUtils.toByteArray(inputStream);
            String mineType = URLConnection.getFileNameMap().getContentTypeFor(file.getName());
            if (mineType == null) {
                mineType = "application/octet-stream";
            }
            String fileName = URLEncoder.encode(file.getName(), "UTF-8");
            fileName = fileName.replaceAll("\+", " ");
            resp.setContentType(mineType);
            resp.addHeader("Content-Disposition", "attachment; filename="Print_" + fileName + """);
            outputStream = resp.getOutputStream();
            outputStream.write(bytes);
        } catch (Exception e) {
            log.error(e.toString());
            StackTraceElement[] sts = e.getStackTrace();
            for (StackTraceElement stackTraceElement : sts) {
                log.warn(stackTraceElement.toString());
            }
            resp.sendError(404, e.toString());
        } finally {
            if (inputStream != null)
                inputStream.close();
            if (file != null && file.exists()) {
                file.delete();
            }
            if (dir != null && dir.exists()) {
                FileUtils.deleteDirectory(dir);
            }
            if (outputStream != null)
                outputStream.close();
        }
    }
<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.5.3/css/bootstrap.min.css">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.15.1/css/all.min.css">
    <link rel="stylesheet" href="https://codemirror.net/lib/codemirror.css">
    <style>
        input::-webkit-outer-spin-button,
        input::-webkit-inner-spin-button {
            -webkit-appearance: none;
            margin: 0;
        }

        .code-area {
            float: left;
            flex-direction: column;
            width: 33%;
            height: 93.5vh;
            border: 1px solid #555;
        }

        .CodeMirror {
            float: left;
            resize: none;
            outline: none;
            width: 100%;
            height: 94vh;
            font-size: 18px;
            padding: 10px;
        }

        .preview-area {
            float: left;
            width: 34%;
            height: 94vh;
            display: flex;
            border: 1px solid #555;
        }

        .preview-area iframe {
            width: 100%;
            height: 100%;
            border: none;
        }
    </style>
</head>

<body>
##<form action="/secure/configPDF/export.jspa" enctype="multipart/form-data">
    <!-- <div class="container-fluid"> -->
    <ul class="nav" style="margin-top: 1vh;"> &nbsp;
        <li class="nav-item">
            <input type="submit" class="btn btn-primary" value="In PDF" onclick="printPDF()" />
        </li> &nbsp;
        <li class="nav-item">
            <input type="button" class="btn btn-primary" value="L?u template"
                   onclick="download(editor.getValue(),'template.vm','text/plain')">
        </li> &nbsp;
        <li class="nav-item">
            <label class="btn btn-primary">
                Chèn template <input type="file" hidden name="fileTemPlate" id="fileTemPlate"
                                     onchange="loadTemplate()" />
            </label>
        </li> &nbsp;
        <li class="nav-item">
            <input type="button" class="btn btn-primary" value="L?u data"
                   onclick="download(editor2.getValue(),'data.json','text/plain')">
        </li> &nbsp;
        <li class="nav-item">
            <label class="btn btn-primary">
                Chèn data <input type="file" hidden name="fileData" id="fileData" onchange="loadData()" />
            </label>
        </li> &nbsp;
        <li>
            <div class="input-group">
                <div class="input-group has-validation"></div>
                <input type="number" class="form-control" name="id" id="idPhase" placeholder="id phase">
                <div class="input-group-prepend">
                    <span class="input-group-text" id="">ID phase</span>
                </div>
            </div>

            </div>
        </li>
        <li>$!errors</li>
    </ul>

    <!-- </div> -->

    <div class="code-area">
        <textarea id="htmlCode" name="htmlLayout" placeholder="Html Code"></textarea>

    </div>

<div class="preview-area">
    <iframe id="preview-window" name="pdfResult"></iframe>
</div>
<div class="code-area">
    <textarea id="jsonCode" name="jsonData" placeholder="Html Code"></textarea>
</div>
##</form>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.16.1/umd/popper.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.5.3/js/bootstrap.min.js"></script>
<script src="https://codemirror.net/lib/codemirror.js"></script>
<script src="https://codemirror.net/mode/xml/xml.js"></script>
<script type="text/javascript">
    function printPDF(){
        let html= editor.getValue();
        let json = editor2.getValue();
        let id = $('#idPhase').val();
        jQuery.ajax({
            url:'/secure/configPDF/export.jspa',
            type:'get',
            datatype:'json',
            data:{
                html:html,
                json:json,
                id:id
            },
            success: function (data){
                var req = new XMLHttpRequest();
                req.send("GET",'/secure/configPDF/export.jspa',true)

            }
        });
    }

    var editor = CodeMirror.fromTextArea(document.getElementById("htmlCode"), {
        lineNumbers: true
    });
    var editor2 = CodeMirror.fromTextArea(document.getElementById("jsonCode"), {
        lineNumbers: true,
        mode: 'application/json'
    });
    editor.on('change', editor => {
        var frame = document.getElementById("preview-window").contentWindow.document;
        frame.open();
        frame.write(editor.getValue());
        frame.close();
    });

    function loadTemplate() {
        let fileToLoad = document.getElementById("fileTemPlate").files[0];
        document.getElementById("fileTemPlate").value = "";
        var fileReader = new FileReader();
        fileReader.onload = function (fileLoadedEvent) {
            var textFromFileLoaded = fileLoadedEvent.target.result;
            editor.setValue(textFromFileLoaded);
        };
        fileReader.readAsText(fileToLoad, "UTF-8");

    }
    function loadData() {
        let fileToLoad2 = document.getElementById("fileData").files[0];
        document.getElementById("fileData").value = "";
        var fileReader = new FileReader();
        fileReader.onload = function (fileLoadedEvent) {
            var textFromFileLoaded = fileLoadedEvent.target.result;
            editor2.setValue(textFromFileLoaded);
            // showPreview();
        };
        fileReader.readAsText(fileToLoad2, "UTF-8");

    }
    function download(data, filename, type) {
        var file = new Blob([data], { type: type });
        if (window.navigator.msSaveOrOpenBlob) // IE10+
            window.navigator.msSaveOrOpenBlob(file, filename);
        else { // Others
            var a = document.createElement("a"),
                    url = URL.createObjectURL(file);
            a.href = url;
            a.download = filename;
            document.body.appendChild(a);
            a.click();
            setTimeout(function () {
                document.body.removeChild(a);
                window.URL.revokeObjectURL(url);
            }, 0);
        }
    }

</script>
</body>

</html>

enter image description here

question from:https://stackoverflow.com/questions/65934054/how-to-get-url-from-networth

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)
Waitting for answers

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...