为了账号安全,请及时绑定邮箱和手机立即绑定

在 Django 中使用 AJAX 上传 CSV 文件

在 Django 中使用 AJAX 上传 CSV 文件

繁星淼淼 2023-03-03 15:00:57
我想使用 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 文件后,当我的console.log文件变量 ( console.log(employeeAttendanceFile);) 没有任何返回。当我从 Django 视图获取 ajax 请求时,它也返回None( print(csv_file))。# views.pyclass ImportEmployeeAttendanceAJAX( View):    def post(self, request):        csv_file = request.FILES.get("employee_attendance_file")        print(csv_file)我究竟做错了什么?
查看完整描述

1 回答

?
POPMUISE

TA贡献1765条经验 获得超5个赞

通过 FormData 对象上传数据时,您必须直接传递它

    data: employeeAttendanceFile,

此外,当您尝试访问文件时,您为上传文件设置的名称必须匹配。

    csv_file = request.FILES.get("attendance-file")


查看完整回答
反对 回复 2023-03-03
  • 1 回答
  • 0 关注
  • 118 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信