form表單和ajax發送文件以及ajax發送json字符串


form表單發送文件

form表單默認傳送格式contentType為urlencoded 當傳送文件的時候我們需要在form表單中 enctype="multipart/form-data"

不然只會發字符串的文件名字放個post中

前端代碼

 

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <link rel="stylesheet" href="/static/bootstrap-3.3.7-dist/css/bootstrap.min.css">
</head>
<body>

<form action="" method="post" enctype="multipart/form-data">
    {% csrf_token %}
    <input type="file" name="myfile">
    <input type="submit">
</form>

</body>
<script src="https://cdn.bootcss.com/jquery/3.4.1/jquery.min.js"></script>
<script src="/static/bootstrap-3.3.7-dist/js/bootstrap.min.js"></script>
</html>

后端代碼

def index(request):
    if request.method == 'POST':
        # form表單傳送文件需要在前端content_type : enctype="multipart/form-data"
        # form表單默認是urlencoded
        file_obj = request.FILES.get('myfile')
        f = open(file_obj.name, 'wb')
        for line in file_obj:
            f.write(line)
        return HttpResponse('ok')
    return render(request, 'text.html')

ajax傳送文件

前端代碼

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <link rel="stylesheet" href="/static/bootstrap-3.3.7-dist/css/bootstrap.min.css">
</head>
<body>
{% csrf_token %}
<input type="file" name='myfile' id="myfile">
<button id="submit">提交</button>
</body>
<script src="https://cdn.bootcss.com/jquery/3.4.1/jquery.min.js"></script>
<script src="/static/bootstrap-3.3.7-dist/js/bootstrap.min.js"></script>


<script>
    $('#submit').click(function () {
        let formDate = new FormData();
        fileObj = $('#myfile')[0].files[0];
        formDate.append('myfile', fileObj);
        formDate.append('username', 'hkk');
        formDate.append('password', '123');

        $.ajax({
            url: '',
            type: 'post',
            {#headers:{"X-csrftoken":$("[name='csrfmiddlewaretoken']").val()},#}
            data: formDate,
            contentType: false,
            processData: false,
            success: function (data) {
                alert(data)
            }
        })
    })

后端代碼

def index1(request):
    if request.method == 'POST':
        print(request.POST)
        file_obj = request.FILES.get('myfile')
        f = open(file_obj.name, 'wb')
        for line in file_obj:
            f.write(line)
        return HttpResponse('ok')
    return render(request, 'text1.html')

 

ajax發送json格式的

需要在ajax中contentTyle:application/json

前端代碼

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <link rel="stylesheet" href="/static/bootstrap-3.3.7-dist/css/bootstrap.min.css">
</head>
<body>
{% csrf_token %}
<button class="btn btn-success" id="my_button">點我</button>
</body>
<script src="https://cdn.bootcss.com/jquery/3.4.1/jquery.min.js"></script>
<script src="/static/bootstrap-3.3.7-dist/js/bootstrap.min.js"></script>

<script>
    $('#my_button').click(function () {
        $.ajax({
            url: '',
            type: 'post',
            contentType: 'application/json',
            {#headers:{"X-csrftoken":$("[name='csrfmiddlewaretoken']").val()},#}
            data: JSON.stringify({'username': 'hkk', 'password': '123'}),
            success: function (data) {
                alert(data)
            }
        })
    })
</script>
</html>

后端代碼

def index2(request):
    if request.method == 'POST':
        print(request.body)
        dic = json.loads(request.body.decode('utf-8'))
        print(dic)
        return HttpResponse('ok')
    return render(request, 'text2.html')

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM