文件的上传和下载功能

1.下载PDF / EXCLE文件

视图函数:

from django.http import HttpRequest, HttpResponse, StreamingHttpResponse
import os
from urllib.parse import quote

def download_pdf(request):
    """打开PDF文件再下载"""
#第一步:构建文件路径(当前路径下+resoure文件夹的Docker入门教程.pdf)
    path = os.path.dirname(os.path.abspath(__file__))
    path = os.path.join(path, 'resources/Docker入门教程.pdf')    

#第二步:打开方式是每次打开1024字节StreamingHttpResponse
file_stream = open(path, 'rb')
file_iter = iter(lambda: file_stream.read(1024), b'')

 #第三步:设置response的文件类型及响应头
    resp = StreamingHttpResponse(file_iter, content_type='application/pdf')
    filename = quote('Docker入门教程.pdf')#如果是中文名,必须处理成百分号编码(quote把中文变为百分号编码)
    resp['content-disposition'] = f'inline; filename="{filename}"'  #设置响应头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

模板页:

下载PDF文件  
下载Excel文件

设置访问路径(vote应用中):

urlpatterns = [
    path('pdf/', views.download_pdf),
    path('excel/', views.download_excel),
]

2.在页面上集成富文本

推荐:wangEditor/kindEditor/CKeditor
不会用,就看使用文档。

(textarea多行文本输入框变为富文本)

  1. 导入Kindeditor到static文件夹
    下载网址:http://kindeditor.net
  2. 模板页

输入内容:

  1. 模型
content = models.TextField(null=True)

  1. 设置urls.py
path('upload/', views.upload_picture)
  1. 将上传的文件放到指定路径的文件夹下

步骤:第一步:拿到image_file文件 第二步:创建image_file文件路径 第三步:将image_file文件的数据写入指定的路径path

@csrf_exempt
def upload_picture(request):
    """富文本上传文件"""

    #第一步:拿到image_file文件
    image_file = request.FILES.get('imgFile')  #]}>
    if image_file:#如果不为空

        #第二步:创建image_file文件路径
        ext = os.path.splitext(image_file.name)[-1]  #image_file.name ->'jay.jpg'  ext->'.jpg'
        filename = uuid.uuid1().hex + ext#全局唯一标识符重新生成文件名filename->'9c782cdc757711e99cb10027136a1c48.jpg'
        url = f'/media/{filename}'
        path = os.path.join(settings.MEDIA_ROOT, filename)# '/home/maggie/PycharmProjects/FriendsMoment/media/9c782cdc757711e99cb10027136a1c48.jpg'

        #第三步:将image_file文件的数据写入指定的路径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.上传文件

  1. 视图函数
def saysomething(request):
    """发朋友圈功能"""
    hint = ''
    if request.method == 'POST':
        content = request.POST.get('content', '') #拿到写入的内容
        pic = request.FILES['picture']  #拿到文件名

        username = request.session.get('username', '')  #拿到保存再session中的username并与数据库中的匹配取出除对象
        user = User.objects.filter(username=username).first()

        record = ShareRecord()
        record.content = content
        record.picture = pic
        record.user = user
        record.save()
        hint = '发表成功'
    return render(request, 'saysomething.html', {'hint':hint})
  1. 映射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)

  1. 渲染页面


    

Friends' Moments

share something    {% if request.session.username %} {{ request.session.username }}   退出登录 {% endif %}
{% for share in shares %}
{{ share.user.username }}
{{ share.content }}
{% endfor %}
  1. 指定上传的路径
MEDIA_ROOT = os.path.join(BASE_DIR, 'media')
MEDIA_URL = '/media/'

你可能感兴趣的:(文件的上传和下载功能)