【问题标题】:Upload a CSV file using AJAX in Django在 Django 中使用 AJAX 上传 CSV 文件
【发布时间】:2021-01-01 06:54:34
【问题描述】:

我想使用 ajax 查询上传 CSV 文件。

模板:

<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,
        });
    });

上传 CSV 文件后,当我 console.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)

我做错了什么?

【问题讨论】:

    标签: javascript python django ajax csv


    【解决方案1】:

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

        data: employeeAttendanceFile,
      
    

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

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

    【讨论】:

    • 还是同样的问题。 csv_file 返回无
    猜你喜欢
    • 2016-02-23
    • 2012-04-25
    • 2014-11-01
    • 2020-11-04
    • 2013-05-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多