标签:mamicode 获取文件 ack 注意 报错 word ESS div 控制台
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Ajax</title> </head> <body> <form> <label for="username">账号</label> <input id="username" type="text"> <label for="password">密码</label> <input id="password" type="password"> </form> <button class="btn">提交</button> <script src="/static/jquery.js"></script> <script> $(‘.btn‘).click(function () { var username = $(‘#username‘).val(); var password = $(‘#password‘).val(); $.ajax({ url:‘/info‘, type:‘post‘, data:{‘username‘:username,‘password‘:password}, success:function () { alert(‘成功‘) }, error:function () { alert(‘失败‘) } }) }) </script> </body> </html>
from django.shortcuts import render # Create your views here. def index(request): return render(request,‘index.html‘) def info(request): if request.method == "POST": print(request.POST) return render(request,‘info.html‘)
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Ajax</title> </head> <body> <form id="form-upload" enctype="multipart/form-data"> <input id="picture" type="file" name="picture"> <!-- 上传多文件,添加multiple --> <!-- <input id="picture" type="file" name="picture" multiple="multiple"> --> </form> <button class="btn">上传</button> <script src="/static/jquery.js"></script> <script> $(‘.btn‘).click(function () { var formData = new FormData(); // 可以传一个form var picture = $(‘#picture‘)[0].files[0]; // 获取文件对象 formData.append(‘picture‘,picture); // 图片 formData.append(‘name‘,‘kidd‘); // 字符串 $.ajax({ url:‘/upload‘, type:‘post‘, data:formData, cache: false, processData: false, // 告诉jQuery不要去处理发送的数据 contentType : false, // 告诉jQuery不要去设置Content-Type请求头 success:function () { alert(‘成功‘) }, error:function () { alert(‘失败‘) } }) }) </script> </body> </html>
from django.shortcuts import render,HttpResponse def upload(request): if request.method == ‘GET‘: return render(request,‘upload.html‘) if request.method == "POST": name = request.POST.get(‘name‘) picture = request.FILES.get(‘picture‘) if picture: path = ‘static/%s‘%picture.name with open(path,‘wb‘) as f: for chunk in picture.chunks(): # 文件小的话,可以直接读取,使用read() f.write(chunk) return HttpResponse(‘‘)
let fo = document.queryselect(‘form‘) let formData = new FormData(fo) console.log(formData) //这样输出,formData里面是没有数据的
标签:mamicode 获取文件 ack 注意 报错 word ESS div 控制台
原文地址:https://www.cnblogs.com/py-peng/p/12643903.html