文件上传

    技术2022-07-11  91

    基于form表单的文件上传

    file_put.html

    <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> <script src="https://ajax.aspnetcdn.com/ajax/jquery/jquery-2.1.4.min.js"></script> </head> <body> <h3>基于form表单的文件上传</h3> <form action="" method="post" enctype="multipart/form-data"> 用户名 <input type="text" name="user"> 头像 <input type="file" name="picture"> <input type="submit"> </form> <h3>基于ajax的文件上传</h3> <form action="" method="post"> 用户名 <input type="text" id="user"> 头像 <input type="file" id="picture"> <input type="button" class="btn" value="ajax"> </form> <script> //ajax文件上传 $('.btn').click(function () { var formdata = new FormData(); formdata.append('user',$('#user').val()); formdata.append('picture',$('#picture')[0].files[0]); $.ajax({ url:'', type:'post', contentType:false, processData:false, data:formdata, success:function (data) { console.log(data) } }) }); </script> </body> </html>

    在ajax上传文件是,要设置这两个参数

    contentType:false, processData:false,

    processData默认情况下会将发送的数据序列化以适应默认的内容类型application/x-www-form-urlencoded,contentType是对编码进行处理。两个参数全部设置False,将文件交给FormData自己处理,ajax层不做任何处理

    views.py

    def file_put(request): if request.method == 'POST': print(request.POST) print(request.FILES.get('picture').name) #下载文件 file_obj = request.FILES.get('picture') with open(file_obj.name,'wb') as f: for line in file_obj: f.write(line) return HttpResponse('ok') return render(request,'file_put.html')

    获取文件要是用request.FILES.get()方法,POST是获取不到的。

    控制台打印结果:

    Processed: 0.009, SQL: 9