【问题标题】:Java Spring - How to upload a file and then return the response in the html Front-end?Java Spring - 如何上传文件然后在html前端返回响应?
【发布时间】:2017-12-21 00:54:06
【问题描述】:

我想使用前端上传一个文件,通过我的控制器访问它并使用 java 检查文件。我要上传的文件是 XML 文件。我用 XML 方案检查它,它工作得很好。

html:

<form method="POST" enctype="multipart/form-data" action="/uploadXML">
    <input name="file" type="file" id="importFile" /> <br>
    <button name="button" type="submit" class="buttonUpload">Upload</button>
</form>

在我的控制器中:

@RequestMapping(value="/uploadXML", method=RequestMethod.POST)
public @ResponseBody String handleFileUpload( 
        @RequestParam("file") MultipartFile file){
        String name = "test11";
    if (!file.isEmpty()) {
        try {
            byte[] bytes = file.getBytes();
            BufferedOutputStream stream = 
                    new BufferedOutputStream(new FileOutputStream(new File(name + "-uploaded")));
            stream.write(bytes);
            stream.close();
            File convertedFile = convert(file);



            //Response response = new Response("Done", name);
            //return response;
           return validateAgainstSchema(convertedFile);

        } catch (Exception e) {
            //Response response = new Response("fail", name);
            //return response;
            return "You failed to upload " + name + " => " + e.getMessage();
        }
    } else {

        //Response response = new Response("fail", name);
        //return response;
        return "You failed to upload " + name + " because the file was empty.";
    }
}

在这里我得到了上传的文件,*convert(file)* 我将 MultiparFile 转换为“普通”文件。使用 validateAgainstSchema() 我检查 XML 文件的格式是否正确。 现在到我不明白的部分。从 * validateAgainstSchema()* 我得到字符串“文件格式正确”或“文件格式不正确”。如果我在控制器中返回此字符串,我的浏览器将重定向到仅包含此字符串的新页面。

但我只希望结果显示在我的单页应用程序中,例如在我的前端。我发现ajax可能是解决这个问题的一种方法。

我的 ajax 代码:

  $( document ).ready(function() {

    var url = window.location;

    // SUBMIT FORM
    $("#customerForm").submit(function(event) {//hier die 1 entfernen!!!!!!!!!!!!!!!!!!!!!!!!!!!
        // Prevent the form from submitting via the browser.
        event.preventDefault();
        ajaxPost();
    });


    function ajaxPost(){

        // PREPARE FORM DATA
    /*  var formData = {
            firstname : $("#firstname").val(), //nachher um Textfelder und so auszulesen
            lastname :  $("#lastname").val()
        }*/

        var text = "..........,";

        // DO POST
        $.ajax({
            //type : "POST",
            contentType : "application/json; charset=utf-8",

            url : url,
            //url : url + "/uploadXml",
            //url:  "/uploadXML",
            data : text,
            //data : JSON.stringify(formData),
            //dataType : 'json',
            success : function(result) {
                //result ist hier mein html document
                if(result.status == "Done"){

                /*  $("#postResultDiv").html("<strong>" + "Post Successfully! Customer's Info: FirstName = " 
                            + result.data.firstname + " ,LastName = " + result.data.lastname + "</strong>"); */

                    $("#postResultDiv").html("<strong>" + "success" + "</strong>");
                }else{
                    $("#postResultDiv").html("<strong>" + "error" + "</strong>");
                }
                console.log(result);
                console.log("test.............");
            },
            error : function(e) {
                alert("Error!")
                console.log("ERROR: ", e);
            }
        });



    }


}) 

这部分我完全不明白。我使用了我在网上找到的一个版本,并对其进行了一些调整。 (我将 id="customerForm" 添加到我的 input type="file" btw. )。现在,如果我按下提交按钮,我的 div 会收到文本“错误”并且什么也没有发生,除了我的 html 被打印在控制台中并且我的 ajax 请求在控制台中打印“成功”。 我的 ajax 代码中的“结果”似乎是我的 html 代码。您能否向我解释一下如何在我的 div 中返回 XML-checking-procedure 的结果?

如果有人可以向我解释这一点,我该如何保存 XML 文件?我稍后在我的项目中需要它。

非常感谢!

【问题讨论】:

    标签: javascript java html ajax spring


    【解决方案1】:

    您可以使用 IFRAME 代替 div 来显示结果。

    <form method="POST" enctype="multipart/form-data" action="/uploadXML" target="result">
        <input name="file" type="file" id="importFile" /> <br>
        <button name="button" type="submit" class="buttonUpload">Upload</button>
    </form>
    <iframe id="result" name="result"></iframe>
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-12-12
      • 2019-11-14
      • 2020-05-11
      • 2013-01-20
      • 1970-01-01
      • 2018-06-19
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多