首先是一個views函數的例子
def get_user_profiles(request):
if request.method == 'POST':
myFile = request.FILES.get("filename", None)
if myFile:
dir = os.path.join(os.path.join(BASE_DIR, 'static'),'profiles')
destination = open(os.path.join(dir, myFile.name),
'wb+')
for chunk in myFile.chunks():
destination.write(chunk)
destination.close()
return HttpResponse('ok')
這是一個簡單的接收客戶端上傳的頭像文件並保存的例子,應該看過這個就已經大體會使用接收文件了
但是這里的filename是客戶端上傳的文件名,也可能是像下面這樣的表單
<input type="file" name="filename" />
如果不知道固定上傳的文件名,想要客戶端上傳什么文件就以其上傳的名字命名可以這么寫
def get_user_profiles(request):
if request.method == 'POST':
if request.FILES:
myFile =None
for i in request.FILES:
myFile = request.FILES[i]
if myFile:
dir = os.path.join(os.path.join(BASE_DIR, 'static'),'profiles')
destination = open(os.path.join(dir, myFile.name),
'wb+')
for chunk in myFile.chunks():
destination.write(chunk)
destination.close()
return HttpResponse('ok')
不過這個是通過輸出request.FILES試出來的,不知道是否有更合適的方法。