ajax上传文件
上传文件的两种方式:
第一种:基于Form表单上传文件
视图层:
def file_put(request):
if request.method=='GET':
return render(request,'file_put.html')
else:
# print(request.POST)
# print(request.POST)
print(request.body) # 原始的请求体数据
print(request.GET) # GET请求数据
print(request.POST) # POST请求数据
print(request.FILES) # 上传的文件数据
# print(request.body.decode('utf-8'))
print(request.body.decode('utf-8'))
print(request.FILES) #这是个字典
file_obj=request.FILES.get('avatar')
print(type(file_obj))
with open(file_obj.name,'wb') as f:
for line in file_obj:
f.write(line)
return HttpResponse('ok')
html中:
<form action="/file_put/" method="post" enctype="multipart/form-data">
用户名:<input type="text" name="name">
头像:<input type="file" name="avatar" id="avatar1">
<input type="submit" value="提交">
</form>
注意:必须指定:enctype="multipart/form-data"
第二种:用ajax上传文件
视图层:
def add_file(request):
if request.method=='GET':
return render(request,'add_files.html')
# 这是个字典
dic_files=request.FILES
myfile=dic_files.get('myfile')
with open(myfile.name,'wb') as f:
# 循环上传过来的文件
for line in myfile:
# 往空文件中写
f.write(line)
return HttpResponse('ok')
模板层:
$("#ajax_button").click(function () {
var formdata=new FormData()
formdata.append('name',$("#id_name2").val())
formdata.append('avatar',$("#avatar2")[0].files[0])
$.ajax({
url:'',
type:'post',
processData:false, //告诉jQuery不要去处理发送的数据
contentType:false,// 告诉jQuery不要去设置Content-Type请求头
data:formdata,
success:function (data) {
console.log(data)
}
})
})
浏览器请求头为:
Content-Type: multipart/form-data; boundary=----WebKitFormBoundaryA5O53SvUXJaF11O2