简体   繁体   中英

How do I append a value to formData on event? (blueimp/jQuery-File-Upload)

I have this code for the moment ->

$('#file').fileupload({
    formData: {
        valueThatChangesOverTime: value,
        staticValue: 0
    },
    maxNumberOfFiles: 1,
    autoUpload: false,
    dataType: 'json',
    add: function (e, data) {
        $('#importFilesBtn').on("click", function () {
            // Set value to formData.valueThatChangesOverTime
            data.submit();
        })
    },
    done: function (e, data) {

    }
});

As you see in my comment I want to append a value to the formData object on a click event but I can't figure out how to do it. It always stays with the initial value.

Has someone done this before and how did you solve it? Thanks.

If the add function is being called as reference to the fileupload options object, then the this will be set to point to the object. With that assumption, the following should work:

add: function (e, data) {
    var fileUploadObj = this
    $('#importFilesBtn').on("click", function () {
        // Set value to formData.valueThatChangesOverTime
        fileUploadObj.formData.valueThatChangesOverTime = 'foo'
        data.submit();
    })
}

edit: another option. I cant think of another way to reference the object from within but another approach would be to take advantage of object linking. Feels a little dirty, but it'd work.

//some external object
foo = {"changeThisValue":"value"}
$('#file').fileupload({
formData: {
    valueThatChangesOverTime: foo,
    staticValue: 0
},
...
add: function (e, data) {
    $('#importFilesBtn').on("click", function () {
        // Set value to formData.valueThatChangesOverTime
        foo.changeThisValue = 'bar'
        data.submit();
    })
}

caveat is, now whatever is handling formdata has to deal with an object instead of directly the value.

I don't like answering my own questions but for the clarity of this question I thinks it's best. I finally found the solution. Instead of trying to "update" the formData I append it myself in the add: event, like this.

add: function (e, data) {
        $('#importFilesBtn').on("click", function () {
            data.formData = {
                valueThatChangesOverTime: myNewValue,
                staticValue: 0
            };
            data.submit();
        })
    },

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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