简体   繁体   English

使用Ajax和Apache CXF上传文件

[英]Upload file using Ajax and Apache CXF

I'm not so familiar with Ajax and client side application (I'm mainly a server side developer). 我对Ajax和客户端应用程序不太熟悉(我主要是服务器端开发人员)。 I need to add to a simple HTML page, a button that uploads a file and sens it to a Apache-CXF service. 我需要在一个简单的HTML页面上添加一个按钮,该按钮可以上传文件并将其感知到Apache-CXF服务。

I don't succeed to make this "hand shake" between client and server. 我没有成功在客户端和服务器之间做出这种“握手”。 I get: 我得到:

java.lang.RuntimeException: org.apache.cxf.interceptor.Fault: Couldn't determine the boundary from the message! java.lang.RuntimeException:org.apache.cxf.interceptor.Fault:无法从消息确定边界!

This is the definition of the service in Java: 这是Java中服务的定义:

@Path("/")
@Produces(MediaType.TEXT_PLAIN)
@Getter
@Setter
@CrossOriginResourceSharing(allowAllOrigins = true)
public class NLPRestService {

    @POST
    @Path("/uploadPosRulesFile")
    @Consumes(MediaType.MULTIPART_FORM_DATA)
    public void uploadFile(@Multipart(value="file", type="text/plain" ) InputStream file) {
        //Here will be the code that handles the file content - I'll know what do with it once I'll succeed to get here
    }
}

This is the HTML file: 这是HTML文件:

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
    "http://www.w3.org/TR/html4/loose.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
        <title>My-App</title>
        <script type="text/javascript" src="js/jquery/jquery-2.1.1.min.js"></script>
        <script type="text/javascript" src="js/jquery/jquery.ui.widget.js"></script>
        <script type="text/javascript" src="js/parseText.js"></script>
        <script type="text/javascript" src="js/uploadPosRules.js"></script>
        <script src="bootstrap/js/bootstrap.min.js"></script>
        <link href="bootstrap/css/bootstrap.css" type="text/css" rel="stylesheet" />
    </head>
    <body>
        <div style="padding: 20px;">
            <h1>my-app</h1>
            <form id="uploadPosRulesform" >
                <div style="width: 700px;">
                    Upload new POS Rules File <input id="fileupload" type="file" name="file" /> 
                    <input  id="submit" value="upload POS RULE file" type="button"  onclick="uploadFiles()" />
                </div>
            </form>
            <!-- Here comes another form that do another thing - irrelevant  -->
            <form id="form">
                ...
            </form>
        </div>
    </body>
</html>

And finally the JavaScript code that does the AJAX call: 最后是执行AJAX调用的JavaScript代码:

function uploadFiles() {
    event.stopPropagation(); // Stop stuff happening
    event.preventDefault(); // Totally stop stuff happening

    // START A LOADING SPINNER HERE

    // Create a formdata object and add the files
    $.ajax({
        url : '../services/nlpService/uploadPosRulesFile',
        type : 'POST',
        data: { file: $('#fileupload').val()},
        cache : false,

        dataType : 'text/plain',

        processData : false, // Don't process the files
        contentType: 'multipart/form-data',
        //contentType : false, // Set content type to false as jQuery will tell the server its a query string request
        success : function(data, textStatus, jqXHR) {
            alert(data);
            if (typeof data.error === 'undefined') {

            } else {
                // Handle errors here
                console.log('ERRORS: ' + data.error);
            }
        },
        error : function(jqXHR, textStatus, errorThrown) {
            // Handle errors here
            console.log('ERRORS: ', jqXHR, textStatus, errorThrown);
            $('#alert').css('display', 'block');
            $('#alert').html(jqXHR.response);
            // STOP LOADING SPINNER
        }
    });

}

It might be really basic issue (because I'm really not fully understand it...) - I'll appreciate your help! 这可能是一个非常基本的问题(因为我真的不完全了解...)-感谢您的帮助!

Thanks a lot 非常感谢

contentType: false,

Try the above. 尝试以上。 This will force jQuery to generate the contentType headers and it will include the boundary information. 这将强制jQuery生成contentType标头,并将包含边界信息。 If you sniff the http message that you are sending to the server you will see that now you are sending something like this 如果您嗅探要发送到服务器的http消息,您将看到现在正在发送类似这样的消息

Content-Type: multipart/form-data; boundary=???

Follow alkis answer and use FormData object (more here: https://developer.mozilla.org/en-US/docs/Web/API/FormData/Using_FormData_Objects ) to pass the file, that worked for me: 遵循alkis答案并使用FormData对象(更多信息: https : //developer.mozilla.org/en-US/docs/Web/API/FormData/Using_FormData_Objects )来传递文件,该文件对我有用:

var fileData = new FormData();
fileData.append('file', file);

And in jquery ajax method: 并在jquery ajax方法中:

data: fileData,

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM