mojibuntu
mojibuntu

Reputation: 307

request.FILES is empty when send ajax file upload request to server

I have a simple form in index.html:

<div id="Competence-form">
    <form id="competence" method="post" action="/" enctype="multipart/form-data">
    {% csrf_token %}                    
        <input type="file" id="Picture-text" name="comp-pic" />
        <input type="button" name="comp-defaultButton" value="Default" />
    </form>
</div>

and here is my ajax request in index.js:

$("#Competence-form").submit(function(event){
    $(".ajaxLogoBoard").show();

    //prevent normal submit when submit button click because check something ...
    event.preventDefault();

    //getting values
    var picture = $("#Picture-text").val();
    var data ={
        picture:picture,
    };

    //send AJAX
    $.ajax({
        url: '/ajax/check',
        data: data,
        dataType: 'json',
        success:function(result){
            // do something
        }

In server I want to use request.FILES but this dictionary is empty :

def competenceCheck(request):
    # ... some code to initialize upload
    # ...
    picture = request.REQUEST['picture']        # this will return the path
    print request.FILES        # but this is empty => <MultiValueDict: {}>
    # ... some code after upload
    # ...

where I do wrong ?

Upvotes: 1

Views: 905

Answers (1)

Daniel Roseman
Daniel Roseman

Reputation: 599560

You can't upload files like that in Ajax - debug logging would show you that $("#Picture-text").val() is empty.

You will need to use some sort of file upload plugin to do it.

Upvotes: 1

Related Questions