返回顶部

Django实现文件上传、文件列表查看、修改、限流和日志记录

Django实现文件上传、文件列表查看、修改、限流和日志记录

本章先简单实现文件的上传,后续会将标题的功能一 一添加上去实现,并且给出远程服务器的不同连接方式【密码和秘钥】,欢迎继续关注。

安装了Django框架

pip install django

 

创建一个Django项目

django-admin startproject file_upload_service

 

创建Django应用

进入项目目录并创建一个Django应用:

cd file_upload_service
python manage.py startapp file_upload

 

配置视图文件

file_upload_service/file_upload/views.py文件中编写视图函数来处理文件上传:

from django.shortcuts import render

def upload_file(request):
    if request.method == 'POST':
        uploaded_file = request.FILES['file']
        # 在这里实现将文件上传到远程服务器的逻辑
        # 你可以使用第三方库(如paramiko)来实现远程文件上传
        with open('uploaded_files/' + uploaded_file.name, 'wb+') as destination:
            for chunk in uploaded_file.chunks():
                destination.write(chunk)
        return render(request, 'file_upload/upload_success.html')
    return render(request, 'file_upload/upload.html')

 

路由urls.py配置

file_upload_service/file_upload/urls.py文件中添加URL配置:

 

from django.urls import path
from . import views

urlpatterns = [
    path('upload/', views.upload_file, name='upload_file'),
]

 

file_upload_service/file_upload_service/urls.py文件中添加应用的URL配置

from django.contrib import admin
from django.urls import include, path

urlpatterns = [
    path('admin/', admin.site.urls),
    path('file_upload/', include('file_upload.urls')),
]
 

 

创建模板文件

file_upload_service/file_upload/templates/file_upload目录下创建upload.htmlupload_success.html模板文件:

upload.html

upload.html模板文件用于展示文件上传表单

<!DOCTYPE html>
<html>
<head>
    <title>文件上传</title>
</head>
<body>
    <h2>上传文件</h2>
    <form method="post" enctype="multipart/form-data">
        {% csrf_token %}
        <input type="file" name="file">
        <button type="submit">上传</button>
    </form>
</body>
</html>

 

upload_success.html

upload_success.html模板文件用于展示文件上传成功页面:

<!DOCTYPE html>
<html>
<head>
    <title>上传成功</title>
</head>
<body>
    <h2>文件上传成功!</h2>
</body>
</html>

 

运行Django开发服务器

python manage.py runserver 0.0.0.0:8080  

 

 

 

posted @ 2023-08-12 22:46  九尾cat  阅读(108)  评论(0编辑  收藏  举报