2

I want to upload a CSV file using ajax query.

Template:

<form id="attendance-form" method="POST" enctype="multipart/form-data">
  <input type="file" id="upload-attendance" name="employee-attendance-file">
</form>

AJAX:

$("#upload-attendance").change(function(e) {
    e.preventDefault();  // disables submit's default action
    var input = $("#upload-attendance")[0];
    var employeeAttendanceFile = new FormData();
    employeeAttendanceFile.append("attendance-file", $('#upload-attendance')[0].files[0]);
    console.log(employeeAttendanceFile);
    $.ajax({
        url: '{% url "attendance:employee-attendance-upload" %}',
        type: 'POST',
        headers:{
            "X-CSRFToken": '{{ csrf_token }}'
        },
        data: {
            "employee_attendance_file": employeeAttendanceFile,
        },
    
        dataType: "json",
        success: function(data) {
            data = JSON.parse(data); // converts string of json to object
        },
        cache: false,
        processData: false,
        contentType: false,
        });
    });

After uploading a CSV file, when I console.log the file variable (console.log(employeeAttendanceFile);) nothing returns. When I fetch the ajax request from django view, it also returns None (print(csv_file)).

# views.py
class ImportEmployeeAttendanceAJAX( View):
    def post(self, request):
        csv_file = request.FILES.get("employee_attendance_file")
        print(csv_file)

What am I doing wrong?

1 Answer 1

1

When uploading data via a FormData object you have to pass it directly

    data: employeeAttendanceFile,
  

Also, the name you set for the file in the upload has to match when you try to access it.

    csv_file = request.FILES.get("attendance-file")
Sign up to request clarification or add additional context in comments.

1 Comment

Still same problem. csv_file returning None

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.