2

This tutorial explains how to upload a file with bottle and normal HTML form. But how do I upload a file to a server with a jquery AJAX call?

HTML

<form id="uploadForm">
file: <input id="fileData" type="file" name="upload" />
<input type="submit" value="Start upload" />
</form>

jQuery

$("#uploadForm").submit(function(event) {
    event.preventDefault();
    $.ajax(
        {
            Type: "POST",
            contentType: false,
            url: "../upload",
            data: //What do i pass here?,
            success: function (data) {
                alert(data);
            }
        });
})

Python Bottle

@app.route('/upload', method='POST')
def do_upload():
    upload = bottle.request.files.query('upload')
    sys.stdout.write(bottle.request.files.get('upload').filename);
    name, ext = os.path.splitext(upload.filename)
    inputfile = open('/srv/http/params/%s'%upload.filename, 'wb')
    inputfile.write(upload.file.read())
    inputfile.close()
    return 'OK'

I'm mainly stuck at what data I should pass over to the AJAX call and how to retrieve this data at Bottle's side thereafter.

Jon Gan
  • 867
  • 1
  • 11
  • 22
  • possible duplicate of [How can I upload files asynchronously with jQuery?](http://stackoverflow.com/questions/166221/how-can-i-upload-files-asynchronously-with-jquery) – Kevin B Dec 03 '13 at 20:24

1 Answers1

0

For supported browsers, you pass a formData object, as you can't upload files from the inputs value directly :

$("#uploadForm").submit(function(event) {
    event.preventDefault();
    var data = new formData(this);
    $.ajax({
        type        : "POST",
        url         : "../upload",
        data        : data,
        contentType : false,
        processData : false
    }).done(function (data) {
        alert(data);
    });
});

for non supporting browsers, you'll need to somehow submit the form through an iFrame

Kevin B
  • 94,570
  • 16
  • 163
  • 180
adeneo
  • 312,895
  • 29
  • 395
  • 388