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?
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")
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.