返回顶部

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 @   九尾cat  阅读(120)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 分享4款.NET开源、免费、实用的商城系统
· 全程不用写代码,我用AI程序员写了一个飞机大战
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· 白话解读 Dapr 1.15:你的「微服务管家」又秀新绝活了
· 上周热点回顾(2.24-3.2)
历史上的今天:
2020-08-12 nginx-1.19.1编译安装
点击右上角即可分享
微信分享提示

目录导航