简体   繁体   中英

Javascript Ajax upload file to Python backend

I got stuck how to make my code work, I am trying to upload file using javascript to my python code.

here my HTML

<div class="form-group">
    <label for="upload_list" class="control-label">Upload List</label>
    <input name="upload_list" id="upload_list" type="file" class="form-control" multiple="true" />
</div>

<a id="make_order" role="button" class="btn btn-primary" href="#">

here my JS that handle the upload.

$("a#make_rfq_order").bind("click", function(ev) {
    var customer_upload_list = $('#upload_list').val();

    ajax.jsonRpc('/shop/order', 'call', {
        'upload_list': customer_upload_list
    });
});

and here my python code

def customer_order(self, **post):
    if post.get('upload_list'):
        .....
        if order and order.id:
            .....
            if post.get('upload_list'):
                .....
                values.update({
                    'name': '{0}_{1}'.format('file', upload_list.filename),
                    })

            order.write(values)

    return True

if I use 'name': '{0}_{1}'.format('file', upload_list), its work, but only handle the file name,

how to get the actual file submited to my server?...

I'm unable to comment, so I'm answering as best I can, but knowing a bit more about your python server would help (are you using a specific framework or did you code your own python server from scratch, etc...)

I think you're sending the path of the file, not the file itself with this part:

    var customer_upload_list = $('#upload_list').val();

Try the below instead:

    var file = $('#upload_list').get(0).files[0];

Also, it looks like you're trying to include support for multiple files. Have you tried building a FormData by iterating over the selected files and adding the FormData to the POST?

Something like this may work, or at least get you in the right direction:

    var files = new FormData();
    for(var i=0;i< $('#upload_list').val().length;i++){
        var file = $('#upload_list').get(0).files[i];
        files.append('files[]', file);
    }

    $.ajax({
      url: 'upload.php',
      type: 'POST',
      data: files
    });

the received data will be in list form on the server side, so remember to alter the code to look for a list.

You may have to play around with other paramaters in the POST, like contentType and dataType or processData, but I think the above is sufficient to get a 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