1.下載PDF / EXCLE文件
視圖函數(shù):
from django.http import HttpRequest, HttpResponse, StreamingHttpResponse
import os
from urllib.parse import quote
def download_pdf(request):
"""打開PDF文件再下載"""
#第一步:構(gòu)建文件路徑(當(dāng)前路徑下+resoure文件夾的Docker入門教程.pdf)
path = os.path.dirname(os.path.abspath(__file__))
path = os.path.join(path, 'resources/Docker入門教程.pdf')
#第二步:打開方式是每次打開1024字節(jié)StreamingHttpResponse
file_stream = open(path, 'rb')
file_iter = iter(lambda: file_stream.read(1024), b'')
#第三步:設(shè)置response的文件類型及響應(yīng)頭
resp = StreamingHttpResponse(file_iter, content_type='application/pdf')
filename = quote('Docker入門教程.pdf')#如果是中文名,必須處理成百分號編碼(quote把中文變?yōu)榘俜痔柧幋a)
resp['content-disposition'] = f'inline; filename="{filename}"' #設(shè)置響應(yīng)頭content-disposition,inline是打開文件,attachment是下載文件
return resp
def download_excel(request):
"""直接下載Excel文件"""
path = os.path.dirname(os.path.abspath(__file__))
path = os.path.join(path, 'resources/老師信息登記表.xlsx')
with open(path, 'rb') as file_stream:
buffer = file_stream.read()
resp = HttpResponse(buffer, content_type='application/vnd.ms-excel')
filename = quote('老師信息登記表.xlsx')
resp['content-disposition'] = f'attachment; filename="{filename}"'
return resp
模板頁:
<a href="/vote/pdf">下載PDF文件</a>
<a href="/vote/excel">下載Excel文件</a>
設(shè)置訪問路徑(vote應(yīng)用中):
urlpatterns = [
path('pdf/', views.download_pdf),
path('excel/', views.download_excel),
]
2.在頁面上集成富文本
推薦:wangEditor/kindEditor/CKeditor
不會用,就看使用文檔。
(textarea多行文本輸入框變?yōu)楦晃谋?
- 導(dǎo)入Kindeditor到static文件夾
下載網(wǎng)址:http://kindeditor.net - 模板頁
<p>輸入內(nèi)容:
<textarea cols="30" rows="10" name="content"></textarea>
</p>
<script src="{% static 'js/jquery.min.js' %}"></script>
<script charset="UTF-8" src="{% static 'js/kindeditor/kindeditor-all-min.js' %}"></script>
<script>
let editor = null
KindEditor.ready(function(K){
editor = K.create('textarea[name=content]', {
width:'720px',
height:'300px',
uploadJson: '/upload/'
})
})
</script>
- 模型
content = models.TextField(null=True)
- 設(shè)置urls.py
path('upload/', views.upload_picture)
- 將上傳的文件放到指定路徑的文件夾下
步驟:第一步:拿到image_file文件 第二步:創(chuàng)建image_file文件路徑 第三步:將image_file文件的數(shù)據(jù)寫入指定的路徑path
@csrf_exempt
def upload_picture(request):
"""富文本上傳文件"""
#第一步:拿到image_file文件
image_file = request.FILES.get('imgFile') #<MultiValueDict: {'imgFile': [<InMemoryUploadedFile: jay.jpg (image/jpeg)>]}>
if image_file:#如果不為空
#第二步:創(chuàng)建image_file文件路徑
ext = os.path.splitext(image_file.name)[-1] #image_file.name ->'jay.jpg' ext->'.jpg'
filename = uuid.uuid1().hex + ext#全局唯一標(biāo)識符重新生成文件名filename->'9c782cdc757711e99cb10027136a1c48.jpg'
url = f'/media/{filename}'
path = os.path.join(settings.MEDIA_ROOT, filename)# '/home/maggie/PycharmProjects/FriendsMoment/media/9c782cdc757711e99cb10027136a1c48.jpg'
#第三步:將image_file文件的數(shù)據(jù)寫入指定的路徑path
with open(path, 'wb') as file_stream:
file_stream.write(image_file.read())
#file_stream-> <_io.BufferedWriter name='/home/maggie/PycharmProjects/FriendsMoment/media/9c782cdc757711e99cb10027136a1c48.jpg'>
data = {'error': 0, 'url': url}
else:
data = {'error': 1}
return JsonResponse(data)
3.上傳文件
- 視圖函數(shù)
def saysomething(request):
"""發(fā)朋友圈功能"""
hint = ''
if request.method == 'POST':
content = request.POST.get('content', '') #拿到寫入的內(nèi)容
pic = request.FILES['picture'] #拿到文件名
username = request.session.get('username', '') #拿到保存再session中的username并與數(shù)據(jù)庫中的匹配取出除對象
user = User.objects.filter(username=username).first()
record = ShareRecord()
record.content = content
record.picture = pic
record.user = user
record.save()
hint = '發(fā)表成功'
return render(request, 'saysomething.html', {'hint':hint})
- 映射url
urlpatterns = [
path('admin/', admin.site.urls),
path('', views.login),
path('register/', views.register),
path('shares/', views.shares),
path('saysomething/', views.saysomething),
path('logout/', views.logout),
]+static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
- 渲染頁面
<body>
<h2>Friends' Moments</h2>
<a href="/saysomething/">share something</a>   
{% if request.session.username %}
{{ request.session.username }}   <a href="/logout/">退出登錄</a>
{% endif %}
<hr>
{% for share in shares %}
<dl>
<dt>
{{ share.user.username }}
</dt>
<dd>{{ share.content }} </dd>
</dl>
<div>
<img src="/media/{{ share.picture }}" height="40" alt="">
</div>
{% endfor %}
<button id="load">加載更多</button>
</body>
- 指定上傳的路徑
MEDIA_ROOT = os.path.join(BASE_DIR, 'media')
MEDIA_URL = '/media/'