django中通過文件和Ajax來上傳文件
一、通過form表單來上傳文件
1.在html模板中
<form action="/index/" method="post" enctype="multipart/form-data">
#在form屬性中寫入enctype="multipart/form-data" 這樣form表單才能支持數據文件的提交 {% csrf_token %} 頭像<input type="file" name="touxiang" id="file"> <br> <label for="name">用戶名</label> <input type="text" id="name" name="username"> <button id="btn">提交</button> </form>
2.在views視圖中寫入
def index(request): if request.method == 'GET': return render(request,'index.html') else: uname = request.POST.get('username') file = request.FILES.get('touxiang') #獲取文件要通過.FILES.get()來獲取文件數據 file_name = file.name path = os.path.join(settings.BASE_DIR,'statics','img',file_name)#來拼接文件內路徑 with open(path,'wb')as f:#將文件寫入本地 for i in file: f.write(i) return HttpResponse(uname)
當在后端接收文件內容的時候用FILES來接收,否者只能接收到文件名,
當用request.FILES.get('file')接收到之后,會接收到一個類似于文件句柄的數據類型,可以通過循環來讀取文件,當文件是視頻的時候,可以用句柄.chunks()來接收固定大小的文件,防止內存被占滿
chunks()默認返回大小經測試位65536b,也就是64kb,最大是2.5MB,是一個生成器
二、Ajax來上傳文件
1.在HTML模板中
$('#btn').click(function () { var formdata = new FormData();#ajax上傳文件的時候,需要這個類型,它會將添加的鍵值對加工成formata的類型 formdata.append('uname',$('#name').val());#添加鍵值對的方法是append,注意寫法,鍵和值之間使用逗號隔開 formdata.append('files',$('#file')[0].files[0]); formdata.append('csrfmiddlewaretoken',$('[name=csrfmiddlewaretoken]').val());#別忘了csrf_tocken $.ajax({ 'url':"{% url 'index' %}", 'type':'post', 'data':formdata,#將添加好的formdata放到data這里 processData:false, //不處理數據 contentType:false,//不設置內容類型 success:function (res) { console.log(res) } }) })
2.在視圖函數中
def index(request): if request.method == 'GET': return render(request,'index.html') else: name = request.POST.get('uname')#獲取POST請求發送過來的數據 file = request.FILES.get('tou')#獲取上傳文件的數據 file_name = file.name#獲取文件名 path = os.path.join(settings.BASE_DIR,'statics','img',file_name)#拼接文件路徑 with open(path,'wb')as f:#將文件寫入本地 for i in file.chunks(): f.write(i)
三、JsonResponse
def index(request): if request.method == 'GET': return render(request,'index.html') else: # dd = {'k1':'v1','k2':'v2'} # dd = json.dumps(dd) # return HttpResponse(dd,content_type='application/json') #在發送的時候發送一個cntent_type='application/json'響應體,發送到模板中的ajax中會自動調用ajax的反序列化,就不需要手動反序列化了 #在python中同樣也有,那就是JsonResponse對象 JsonResponse對象是HttpResponse的子類,專門用來生成JSON編碼的響應 from django.http import JsonResponse #導入JsonResponse dd = {'k1':'v1','k2':'v2'} return JsonResponse(dd) #這樣就不需要自己手動序列化了,也不需要自己手動寫響應體了 dd = [11,22,33] return JsonResponse(dd,safe=False)#當序列化的是一個非字典的時候就需要safe=false,
四、json序列化時間日期類型的數據的方法
import json from datetime import datetime from datetime import date #對含有日期格式數據的json數據進行轉換 class JsonCustomEncoder(json.JSONEncoder): def default(self, field): if isinstance(field,datetime): return field.strftime('%Y-%m-%d %H:%M:%S') elif isinstance(field,date): return field.strftime('%Y-%m-%d') else: return json.JSONEncoder.default(self,field) d1 = datetime.now() dd = json.dumps(d1,cls=JsonCustomEncoder) #當再調用json的時候就不能只寫要序列化的數據了,在后面要寫上cls=JsonCustomEncoder print(dd)

浙公網安備 33010602011771號