Views
# form表单文件上传 def file_put(request): print('------',request.FILES) if request.method == 'POST': file_obj = request.FILES.get('file') with open(file_obj.name,'wb') as f: for line in file_obj: f.write(line) return HttpResponse('ok') return render(request,'file.html') # 基于ajax文件上传 def ajax_put_file(request): if request.method =='POST': file_obj = request.FILES.get('avator') with open(file_obj.name, 'wb') as f: for line in file_obj: f.write(line) return HttpResponse('OK') return render(request,'file.html')
HTML中
<form action="" method="post" enctype="multipart/form-data"> {% csrf_token %} 用户名<input type="text" name="user" id="user"> 头像<input type="file" name="file"> <input type="submit"> </form> --------------<hr>------------ 用户名<input type="text" id="user_aj"> 头像<input type="file" id="avator"> <input type="button" id="btn_aj" value="ajax提交">
jquery
<script src="http://libs.baidu.com/jquery/2.0.0/jquery.min.js"></script> <script> $('#btn_aj').click(function () { var formdata = new FormData(); formdata.append('user',$('#user_aj').val()); formdata.append('avator',$('#avator')[0].files[0]); //获得input对象中得文件 $.ajax({ url:'/ajax_put_file/', type:'post', data:formdata, contentType:false, processData:false, success:function (data) { console.log(data) } }) }) </script>
重点
1、基于ajax传输文件,在jquery的ajax中,首先需要创建一个formdata对象var formdata = new FormData()
然后在formdata增加数据,formdata.append('avator',$('#avator')[0].files[0]),
添加前端选择文件的文件对象最后在ajax中添加额为两个参数contentType:false,processData:false,
2、在后端取得文件数据 request.FILES.get()