django 基於form表單上傳文件和基於ajax上傳文件
阿新 • • 發佈:2018-12-05
.py ons strong code .ajax lin con html $.ajax
一、基於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界面一樣的不需要改動,前臺需呀改動
django 基於form表單上傳文件和基於ajax上傳文件