使用django的APP在前端上传excel通过post传给后端读取并打印

文章目录

  • 前言
  • 前端
  • 后端

前言

备研了,博客许久未更了,但是学期末的大作业,遇到了问题并成功解决了,不得不记录一下。

前端

<form method="post" enctype="multipart/form-data" action="/insurance/upload_result">
	<input type="file" name="excel_file">
	<button type="submit">导入button>
form>

传数据表单必不可少
input用于文件类的上传,相当于先让前端收到这份文件
button用于表单的发送(submit 提交很好理解)

表单中的 action=“/insurance/upload_result”>
表明我们要将文件数据发送给谁接受。

那么我们后端代码如下:

后端

urls.py:

from django.urls import path
from . import views
urlpatterns = [
    # http://127.0.0.1:8000/insurance/insurance
    path("upload_result", views.upload_result),
]

需要正确配置好我们发送请求的路由,不然接收不到。
ps:当你在APP里写路由时,一定千万必须不能忘记把APP那层加上(指在前端表单的action中)
因为我这里是在APP接受post,因此虽然路径是upload_result
但是实际上的访问路径需要加上APP那层,就是:/insurance/upload_result

然后我们视图函数配置好我们接受和处理送来的数据的函数即可:

def upload_result(request):
    if request.method == 'POST':
        try:
            f = request.FILES.get('excel_file')
            excel_type = f.name.split('.')[1]
            if excel_type in ['xlsx', 'xls']:
                user_data = pd.read_excel(f)
            print(user_data)
        except:
            error = '解析excel文件或者数据插入错误'
            return render(request, 'index.html', {"error": error})
        
    return render(request,'index.html')

使用django的APP在前端上传excel通过post传给后端读取并打印_第1张图片
可以看到后台成功接收到了文件,并且打印出来了
状态码200也表示成功传输了。

因此,路由配置一定要注意!!!尤其是在APP中别忘记APP那层,同时最后多了/也是不行的,

你可能感兴趣的:(Django,django,前端,excel)