我想使用ajax查询上传CSV文件
模板:
<form id="attendance-form" method="POST" enctype="multipart/form-data">
<input type="file" id="upload-attendance" name="employee-attendance-file">
</form>
阿贾克斯:
$("#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,
});
});
上传CSV文件后,当Iconsole.log
文件变量(console.log(employeeAttendanceFile);
)不返回任何内容。当我从django视图获取ajax请求时,它还返回None
(print(csv_file)
)
# views.py
class ImportEmployeeAttendanceAJAX( View):
def post(self, request):
csv_file = request.FILES.get("employee_attendance_file")
print(csv_file)
我做错了什么
通过FormData对象上载数据时,必须直接传递数据
此外,当您尝试访问文件时,您在上载中为文件设置的名称必须匹配
相关问题 更多 >
编程相关推荐