前端学习心得(20211203)
任务:前端设置一个表单用来收集用户选择的文件,用户选择后将选择的文件作为参数,使用ajax封装一个post请求发送给服务器,也就是flask后端,后端获取该文件并复制到服务器上,也就是复制文件,然后返回‘ok’,前端打印结果反馈用户。
flask:
from flask import Flask, render_template, request, jsonify
import os
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:
f = request.files[source_file]
path = os.path.join(os.path.dirname(os.path.abspath(__file__)), f.name + .txt)
with open(path, wb) as file:
file.write(f.read())
return ok
except Exception as ex:
print(ex)
raise ex
if __name__ == "__main__":
app.run(port=7855, host=127.0.0.1)
html:
<html> <head> <title> Home Page </title> </head> <body> <button id="btn">按钮</button> <form> <input id="select_district1" type="file"> </form> </body> <script type="text/javascript" src="/static/js/src/jquery.min.js"></script> <script type="text/javascript" src="/static/js/home_page.js"></script> </html>
js:
var originUrl = "http://127.0.0.1:7855"
window.onload = function () {
// 选择文件
$(document).on("change", "#select_district1", 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,// 这个也是必须的,不然会报错
dataType: text,//这里是返回类型,一般是json,text等
success: function (data) {
alert("success");
},
error: function () {
alert("error occurred");
}
})
});
// 事件点击
$("#btn").click(
function () {
alert("click!!")
}
)
}
