一、基于form表单上传文件
1、html里是有一个input type="file" 和 ‘submit’的标签
2、vies.py
def fileupload(request): if request.method == 'POST': print(request.POST) print(request.FILES) # from django.core.files.uploadedfile import InMemoryUploadedFile print(type(request.FILES.get('myfile'))) myfile = request.FILES.get('myfile') name = myfile.name print(name) with open(name,'wb') as f: # for line in myfile.chunks(): # f.write(line) for line in myfile: f.write(line) return HttpResponse('文件上传成功')
二、基于JSON上传文件
$("#ajax_button").click(function () { var formdata=new FormData() formdata.append('name',$("#id_name2").val()) formdata.append('myfile',$("#myfile")[0].files[0]) $.ajax({ url:'', type:'post', processData:false, //告诉jQuery不要去处理发送的数据 contentType:false,// 告诉jQuery不要去设置Content-Type请求头 data:formdata, success:function (data) { console.log(data) } }) })
def fileupload(request): if request.method == 'POST': print(request.POST) print(request.FILES) # from django.core.files.uploadedfile import InMemoryUploadedFile print(type(request.FILES.get('myfile'))) myfile = request.FILES.get('myfile') name = myfile.name print(name) with open(name,'wb') as f: # for line in myfile.chunks(): # f.write(line) for line in myfile: f.write(line) return HttpResponse('文件上传成功')
三、综上所述
基于form表单上传文件和基于ajax上传文件后端view界面一样的不需要改动,前台需呀改动