简体   繁体   中英

How can I submit a multipart form via Ajax into web2py? (form includes file(s))

I have to process an arbitrary file, not necessarily related to a model. So, let's say I want full control over the form and the data it sends. I have a "manually built" form in the controller:

the_form = FORM(INPUT(_type='file', _name='image'),
                INPUT(_type='text', _name='sometext'),
                _action=URL('controller', 'upload_test'),
                _method='post')

In the view, I display the form normally, with, let's say {{=the_form}} Then, by using a simple jQuery, I try to submit the form via Ajax.

However, I've encountered the following problems:

  • the file doesn't seem to get through to the server;
  • eventually I've found that there is a request._body.file that appears to contain the uploaded file, but I get "access denied" when trying to read it (it's a temporary file); and it just doesn't feel right using it.

Why doesn't the file get through to the server side in the regular request.vars or request.post_vars ? Any help is greatly appreciated. Thank you.

I managed to resolve this myself. The "trick", if I may say so, was to send the data to the server in a proper way, by serializing the form data differently. Here's a brief description of that:

(function($) {
$.fn.serializefiles = function() {
    var obj = $(this);
    var formData = new FormData();
    var params = $(obj).serializeArray();

    $.each($(obj).find("input[type='file']"), function(i, tag) {
        $.each($(tag)[0].files, function(i, file) {
            formData.append(tag.name, file);
        });
    });

    $.each(params, function (i, val) {
        formData.append(val.name, val.value);
    });
    return formData;
};
})(jQuery);

var form_request_data = $("form").serializefiles();

var ajaxParams = {
        type: "POST",
        url : target_url,
        data : form_request_data,
        cache: false,
        contentType: false,
        processData: false,
        async : true
};

$.ajax(ajaxParams).done( function(request_result) {
 ... 
}

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