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')