knockoutjs:使用ajax调用发送MultipartFile和其他数据

时间:2017-03-24 15:13:38

标签: jquery ajax knockout.js kendo-ui kendo-upload

我有这个简单的形式:

<form id="form">
<ul>
    <li><label>Picture</label>
        <input id="upload" name="Picture" class="k-textbox" data-bind="value: picture" type="file"/>
    </li>
    <li>
        <label>Name</label>
        <input type="text" data-bind="value: name" id="name" class="k-textbox" />
    </li>
    <li>
        <label>Surname</label>
        <input type="text" data-bind="value: surname" id="surname" class="k-textbox" />
    </li>
</ul>
</form>

和我的viewModel:

var ViewModel = funtion(){
    this.picture = ko.observableArray();
    this.name = ko.observable();
    this.surname = ko.observable():
};

使用knockout var picture只包含文件的路径,使用kendo我可以使用此代码获取文件:

var kendoUpload = $("#upload").kendoUpload({
    multiple: false,
});
var files = kendoUpload.data("kendoUpload").getFiles()[0];

我希望将所有数据发送到java控制器。 我尝试了更多的控制器...这是最后一个三:

@RequestMapping(value = "addUser")
public String addUser(MultipartHttpServletRequest request, @RequestBody User user, @RequestParam("picture") MultipartFile[] uploadFiles)
        throws Exception {

    return "finish";
}

User是一个带有String name,surname;

的简单类

这是我的ajax电话:

$.ajax({
url : "./user/addUser",
type : "POST",
dataType :'multipart/form-data',
contentType : "application/json",
useProxy: false,
data : data
 }).done(function(response) {
    console.log(response);
 });

发送数据和设置ajax调用的正确方法是什么? 如何通过knockout的数据绑定而不是通过kendoUpload上传文件?

1 个答案:

答案 0 :(得分:1)

不确定我是否完全理解,但这是我在需要发送更多数据而不仅仅是MultipartFile数组时所做的事情。

function submitUser(user) {

    // input where the files were uploaded to
    var filesToUpload = filesInput[0].files;

    // new form with our files and our user object
    var formData = new FormData();
    formData.append("productMedia", filesToUpload);
    formData.append("user", user);

    // ajax request
    var request = $.ajax({
        url: './user/addUser',
        data: formData,
        // Tell jQuery not to process data or not to worry about content-type
        // You *must* include these options in order to send MultipartFile objects
        cache: false,
        contentType: false,
        processData: false,
        method: 'POST',
        type: 'POST',
        success: function() {
            // do something
        },
        error: function () {
            // do something
        }
    });
}