简体   繁体   中英

Post file using jquery in Django

I want to post a csv file to django view using jquery

<form  id="form" enctype="multipart/form-data" >
<input type="file" name="ListFile" id="ListFile" />
<button type="button" onclick="csv_send">upload</button>
</form><br>


js is:

function csv_send(){
var data = {
'csrfmiddlewaretoken' : $('input[name=csrfmiddlewaretoken]').val(),
'data': $("#ListFile").val()
}
/*$.ajax({
  type: 'POST',
  url:'/list/create/',
  cache:false,
  dataType:'json',
  data:data,
  success: function(result) {
     console.log("ok")
    }
 });*/
}


django views.py:

def createlist(request):
    if request.method == 'POST':
        file =  request.FILES


here not getting file.
I know getting file using form action.But here i want to post file through javascript because i want response back to javascript after success. Clearly i want that file in views.py by request.FILES

When uploading files, your form must have this attribute:

enctype='multipart/form-data'

like this:

<form  id="form" enctype='multipart/form-data'>

This might help you understand.

You have to use a FormData object and a slightly modified version of basic ajax post:

    var data = new FormData();
    var file = null;

    //when uploading a file take the file
    $("#your-file-input-id").on("change", function(){
        file = this.files[0]
    });

    //append the file in the data
    data.append("file", file);

    //append other data
    data.append("message", "some content");

    $.ajax({
        url: '/path',
        type: 'POST',
        data: data,
        contentType: false,
        processData: false,
        success: function (data, status, xhr) {
            //handle success            },
        error: function (data, status, xhr) {
            //handle error
        }

    });

In Django you will find the file in request.FILES['file'] . I hope this is helpful.

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