視圖層:html
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中:ajax
<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>
視圖層:瀏覽器
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')
模板層:app
$("#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=----WebKitFormBoundaryA5O53SvUXJaF11O2post