怎样通过Jquery给后端Django服务上传文件

1. form类

class TianqiUploadForm(forms.Form):
    tianqi_file = forms.FileField(label="上传文件")

2. 前端html

{% load crispy_forms_tags %}

<form method="post" id="importForm" novalidate enctype="multipart/form-data">
    {% csrf_token %}
    <div class="modal-body">
        {{ form|crispy }}
        <br />
        <button type="button" class="btn btn-secondary" data-dismiss="modal">关闭</button>
        <button type="button" id="btnSubmit" class="btn btn-primary">提交</button>
    </div>
</form>

3. 前端js

{% block myjavascript %} 
<script>
    $(function(){
        $("#btnImport").click(function(){
            $("#importTianqiData").modal('toggle')
        })

        $("#btnSubmit").click(function(){
            let data = new FormData(document.getElementById("importForm"));
            $.ajax({
                url:"",
                type:"POST",
                data:data,
                success:function(data){
                    alert("成功");
                    $("#importTianqiData").modal('toggle')
                },
                processData: false,
                contentType: false
            })
        })
    })
</script>
{% endblock %}

注意:

  1. new FormData(document.getElementById("importForm"))
    这一句,是不能直接用$("#importForm")的
    参照链接:https://blog.csdn.net/yehuaner33/article/details/108279727

  2. 这两句是必须加的

                processData: false,
                contentType: false

解释:
来自:https://stackoverflow.com/questions/16501524/ajax-formdata-illegal-invocation

jQuery tries to transform your FormData object to a string, add this to your $.ajax call:

processData: false,
contentType: false

4. django代码

def tianqi_agg(request):
    form = forms.TianqiUploadForm()
    print(request.FILES)
    if request.method == "POST":
        form = forms.TianqiUploadForm(request.POST, request.FILES)
        if form.is_valid():
            print("is ok")
            tianqi_file = request.FILES.get("tianqi_file")
            df = pd.read_excel(tianqi_file)
            print(df.head())
            print(tianqi_file)
    print(form.errors)
    return render(request, "tianqi_agg.html", {"form":form})

5.效果

file

file

Leave a Comment