Django实现上传文件并读取分析;Django捕获前端上传参数供view.py中函数使用

需求

在做比赛时要做的一个功能:用户在网页端上传文本文件(txt、docx、pdf等),然后自己写的python程序进行文本分析,将分析的结果再展示给用户。
大概分为几个步骤(都是在django的框架下):

  1. 写一个简易网页,用户上传文件(pdf、docx),读取存储到MySQL中
  2. python读取MySQL中存储的文本数据并进行分析
  3. 将分析的结果可视化展现给用户

前端网页用于用户上传文件

upload_file.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>上传文件</title>
    <style>
        /* 为所有按钮和所有具有类 red 的元素设置样式 */
        button, .red {
            background-color: red;
            color: white;
            border: none;
            padding: 10px 20px;
            font-size: 16px;
        }
        
        /* 为所有按钮在鼠标悬停时设置样式 */
        button:hover {
            background-color: darkred;
        }
        
        /* 为所有 h1 元素设置样式 */
        h1 {
            font-size: 24px;
            font-weight: bold;
            text-align: center;
        }
        
        /* 为所有表单输入框设置样式 */
        form input[type="text"], form input[type="file"] {
            width: 50%;
            height: 30px;
            font-size: 16px;
            border: 1px solid gray;
            padding: 5px 10px;
        }
        
        /* 为所有表单按钮设置样式 */
        form input[type="submit"] {
            width: 20%;
            height: 40px;
            font-size: 16px;
            background-color: blue;
            color: white;
            border: none;
        }
        
        /* 为表单的背景设置渐变色 */
        form {
            background-color: linear-gradient(to right, lightgray, gray);
            border-radius: 10px;
            box-shadow: 0 4px 8px 0 rgba(0, 0, 0, 0.2), 0 6px 20px 0 rgba(0, 0, 0, 0.19);
        }
        form {
            display: flex;
            flex-direction: column;
            align-items: center;
        }
    </style>
</head>
<body>
    <form method="post" action="" enctype="multipart/form-data">
        {% csrf_token %}
        <h1>上传文本文件测试</h1>
        <input type="file" name="file"><br>
        演讲主题<input type='text' name='topic'><br>
        <input type="submit" value="上传">
        <br>
    </form>
    <!--   href中的参数是在url中对应的函数名字 -->
    <!--      url.py中有这个路径: path("upload/TextAnalyse/", views.TextVisualizaton) -->
    <a href="TextAnalyse">   
        <button>分析</button>
        <!--点击分析会调用view.py中的TextVisualizaton函数-->
    </a>
</body>
</html>

网页如图所示:
在这里插入图片描述

获取在网页端上传的文件和参数值

这部分的函数定义在view.py中;代码的说明和注意事项写在注释当中

def upload_file(request):
    if request.method == "POST":
     	# 获取上传的文件 
        uploaded_file = request.FILES['file']
        if uploaded_file.size == 0:
            return HttpResponse("请上传有内容的文件!")
        _, file_extension = os.path.splitext(uploaded_file.name)
        # 读取文件的内容
        file_content = uploaded_file.read()
        # 因为我后面的处理函数只能处理txt文件,所以事先定义了pdf转txt,docx转txt的函数
        # convert_pdf_to_txt和word_to_txt为事先定义好的
        if file_extension == '.pdf':
            text_list = convert_pdf_to_txt(file_content)
        elif file_extension == '.docx':
            text_list = word_to_txt(file_content)
        else:
            return f'错误:{file_extension}类型的文件暂不支持,请上传.docx文件或.pdf文件'
        # 将文本列表转换为字符串
        text_str = '\n'.join(text_list)
        # 获取前端传入的字符串参数topic
        global topic_
        topic_=request.POST.get('topic')
        # 连接数据库
        # 这里不要像我这样写,使用django的models直接导入
        conn = pymysql.connect(host="localhost", port=3306, user="root", passwd="xxx", db="xxx")
        cursor = conn.cursor()
        # 执行 SQL 语句将文本文件的内容写入数据库中
        sql = "insert into `test_txt`(text) values(%s)"
        cursor.execute(sql, text_str)
       # 提交事务
        conn.commit()
        # 关闭连接
        cursor.close()
        conn.close()
        # 下面html的名字需要是第一部分的那个文件名字
        return render(request, "../templates/upload_file.html")
    else:
        return render(request, "../templates/upload_file.html")

在前端点击上传之后,可以发现数据库中已经多了一条文本数据。
这里的参数topic是供view.py的其他函数使用,所以这里使用了global关键字

word、pdf转txt的函数可以参考我另一篇博客中的记录👉博客的最后部分

也是django小白,自己慢慢摸索的,记录博客是怕自己忘了,若对你有帮助那就更好了!
我的邮箱:k1933211129@163.com,CSDN私信很少看,欢迎各位大佬不吝赐教~

  • 1
    点赞
  • 9
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值