Django上傳文字檔案
阿新 • • 發佈:2019-02-11
前置條件:
1.建立了名為mydjango的project
2.建立了名為learn的app
3.learn中建立了模板資料夾templates
專案結構圖如下:
具體流程如下:
1.在應用learn中新建forms.py,編寫檔案上傳form物件:
from django import forms
class UploadFileForm(forms.Form):
title = forms.CharField(max_length=50)
file = forms.FileField()
2.建立package工具包,定義一個檔案處理工具模組FileTools.py,遍歷UploadedFile.chunks(),而不是使用read(),能確保大檔案並不會佔用系統過多的記憶體:
def handle_upload_file(file):
with open('name.txt', 'wb+') as destination:
for chunk in file.chunks():
destination.write(chunk)
3.views.py中定義處理檔案上傳的controller方法:
from django.http import HttpResponse
from django.http import HttpResponseRedirect
from .forms import UploadFileForm
from learn.tools.FileTools import handle_upload_file
'''
上傳檔案處理
'''
def upload_file(request):
if request.method == 'POST':
form = UploadFileForm(request.POST, request.FILES)
if form.is_valid():
handle_upload_file(request.FILES.get('file', None))
ftemp = request.FILES.get('file' , None)
print('ftemp: ', ftemp)
return HttpResponseRedirect('/success/')
else:
form = UploadFileForm()
return render(request, 'upload.html', {'form':form})
'''
上傳成功跳轉處理
'''
def uploadFileResult(request):
result = u'成功......'
return render(request, 'success.html', {'result':result})
4.templates中新增模板檔案success.html和upload.html:
success.html:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>檔案上傳結果</title>
</head>
<body>
檔案上傳成功
</body>
</html>
upload.html:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>檔案上傳</title>
</head>
<body>
<form method="post" enctype="multipart/form-data">
{% csrf_token %}{{ form }}
<input type="submit" value="提交"/>
</form>
</body>
</html>
5.新增請求url,修改mydjango下的urls.py:
urlpatterns = [
url(r'^$', learn_views.index, name='home'),
url(r'^success/$', learn_views.uploadFileResult, name='success'),
url(r'^uploadFile/$', learn_views.upload_file, name='upload'),
#url(r'^$', learn_views.index),
#url(r'^$', learn_views.home, name='home'),
#url(r'^form/$', learn_views.form, name='form'),
#url(r'^add/$', learn_views.add, name='add'),
#url(r'^add_a_b/(\d+)/(\d+)/$', learn_views.add2, name='add2'),
#url(r'^hello/$', learn_views.hello),
url(r'^admin/', admin.site.urls),
]
6.啟動執行,瀏覽器中輸入http://127.0.0.1:8000/uploadFile/:
選擇檔案上傳,結果為:
7.在mydjango下,可以看到name.txt檔案,檔案內容為上傳的檔案內容: