实现web前端上传excel文件到flask服务器 您所在的位置:网站首页 Flask服务怎么做主从 实现web前端上传excel文件到flask服务器

实现web前端上传excel文件到flask服务器

2023-07-26 02:53| 来源: 网络整理| 查看: 265

这里有两种方法:1. html方式;2. javascript方式(jQuery+ajax)

第1种方法:html方式

这种方法直接通过设计form表单相关属性实现将excel表格上传到服务器,并在服务器端通过xlrd等excel文件处理模块读取数据。

前端页面示例代码(注意:form元素中的enctype="multipart/form-data"不可或缺) Title 后台示例代码展示 @app.route('/toexcel',methods = ['GET','POST']) def toExcel(): if requesthod == 'POST': file = request.files.get('file') f = file.read() data_file = xlrd.open_workbook(file_contents=f) # sheet1 table = data_file.sheet_by_index(0) # print(table) # print(table.nrows) # 获取该sheet中的有效行数 for row_num in range(0, table.nrows): print(table.row_values(row_num)) return redirect('/index') # 根据具体问题返回不同内容 return redirect('/index') # 根据具体问题返回不同内容 第2中方法: javascript方式(jQuery+ajax)

这种方法利用FormData获得数据,通过ajax将数据上传到flask服务器端,再通过xlrd等excel文件处理模块读取数据。

前端页面关键代码(注意:form元素中的enctype="multipart/form-data"不可或缺) function upload_file(fileObj) { let form = new FormData(); // FormData 对象 form.append("file", fileObj); // 文件对象 console.log(form.get('file')); $.ajax({ url: '/toexcel', //url地址 type: 'POST', //上传方式 data: form, // 上传formdata封装的数据 dataType: 'JSON', cache: false, // 不缓存 processData: false, // jQuery不要去处理发送的数据 contentType: false, // jQuery不要去设置Content-Type请求头 success:function (data) { //成功回调 console.log(data); // 根据具体问题替换代码 }, error:function (data) { //失败回调 console.log(data); // 根据具体问题替换代码 } }); } $('#file_name').change(function (e) { let fileName = e.target.files[0];//js 获取文件对象 // console.log(fileName); if(fileName !== undefined){ let file_typename = fileName.name.substring(fileName.name.lastIndexOf('.')); if (file_typename === '.xls') { upload_file(fileName); }else{ console.log("请选择正确的文件类型!") } }else{ console.log("请选择正确的文件!") } }); 后台示例代码展示 @app.route('/toexcel', methods=['GET', 'POST']) def toExcel(): if requesthod == 'POST': data = request.files.get('file') f = data.read() data_file = xlrd.open_workbook(file_contents=f) # sheet1 table = data_file.sheet_by_index(0) # 输出每一行的内容 # table.nrows获取该sheet中的有效行数 for row_num in range(0, table.nrows): print(table.row_values(row_num)) return ... # 根据具体问题返回数据 return ... # 根据具体问题返回数据


【本文地址】

公司简介

联系我们

今日新闻

    推荐新闻

    专题文章
      CopyRight 2018-2019 实验室设备网 版权所有