【问题标题】:knockoutjs: send MultipartFile and other data with ajax callknockoutjs:使用 ajax 调用发送 MultipartFile 和其他数据
【发布时间】:2017-08-17 14:30:13
【问题描述】:

我有这个简单的形式:

<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>

和我的视图模型:

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

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 调用的正确方法是什么? 如何通过敲除的数据绑定而不是通过kendoUpload获取文件?

【问题讨论】:

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


【解决方案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
        }
    });
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-09-20
    • 1970-01-01
    • 1970-01-01
    • 2015-01-06
    • 2014-05-19
    • 2023-03-10
    • 2014-01-17
    • 2016-11-24
    相关资源
    最近更新 更多