前端学习心得(20211206)
任务:基于20211203的任务继续优化,原任务为“前端设置一个表单用来收集用户选择的文件,用户选择后将选择的文件作为参数,使用ajax封装一个post请求发送给服务器,也就是flask后端,后端获取该文件并复制到服务器上,也就是复制文件,然后返回‘ok’,前端打印结果反馈用户。”这次的任务优化了文件上传按钮,使用自定义的按钮取代浏览器的默认样式。另外还优化了标题样式。
谷歌浏览器的默认样式:
预期样式:
html:
<!DOCTYPE html> <html> <head> <title> Score Statistics Tool </title> <meta http-equiv="Content-Type" content="text/html; charset=utf-8"> </head> <link rel="stylesheet" href="/static/css/HomePage.css"> <body> <div class=title><p><b> Welcome to use Score Statistics Tool </b></p></div> <div id=upload_file> upload file<input id="upload_file_plug_in" type="file"> </div> </body> <script type="text/javascript" src="/static/js/src/jquery.min.js"></script> <script type="text/javascript" src="/static/js/HomePage.js"></script> </html>
css:
.title { font-size: 50px; text-align: center; } #upload_file { width: 150px; /* 文本边框的宽度 */ height: 23px; /* 文本边框的高度 */ border: solid 1px #e6e6e6; /* 文本边框的类型、宽度、颜色 */ text-align: center; /* 文本在边框里的位置居中 */ overflow: hidden; /* 后续子元素超过了边框的处理方法,这里是隐藏 */ margin:0 auto; /* 文本边框居中 */ } #upload_file_plug_in { opacity: 0; /* 元素完全透明,透明程度从0到5 */ position: relative; /* 位置方式为相对位置,表示相较于默认的位置 */ top: -21px; /* 相较于默认位置上移21px */ }
js:
var originUrl = "http://127.0.0.1:7855" var upload_file_success = false window.onload = function () { // 选择文件 $(document).on("change", "#upload_file_plug_in", function (e) { var file = e.target.files[0]; var formData = new FormData(); formData.append("source_file", file); $.ajax({ type: "POST", url: originUrl + "/upload_file", data: formData, contentType: false,// 当有文件要上传时,此项是必须的,否则后台无法识别文件流的起始位置 cache: false, processData: false,// 一定要有,不然报错,原因未知 success: function () { upload_file_success = true; alert("success"); }, error: function () { alert("error occurred"); } }) }) }
flask后端:
from flask import Flask, render_template, request, jsonify import os SCORE_EXCEL_FILE_PATH = None app = Flask(My Flask, template_folder=template, static_folder=static) @app.route(/, methods=[GET]) def home_page(): return render_template(HomePage.html) @app.route(/upload_file, methods=[POST]) def upload_file(): try: global SCORE_EXCEL_FILE_PATH f = request.files[source_file] SCORE_EXCEL_FILE_PATH = os.path.join(os.path.dirname(os.path.abspath(__file__)), f.name + .txt) with open(SCORE_EXCEL_FILE_PATH, wb) as file: file.write(f.read()) # 这里一定要有返回值,且类型仅限为字符串,元祖,json,不然flask会报错 return ok except Exception as ex: print(ex) raise ex if __name__ == "__main__": app.run(port=7855, host=127.0.0.1)
下一篇:
Actor模型和CSP模型的区别