赞
踩
需要注意的点:
1.跨域问题:在fastapi中设置即可(见代码)
2.字段一致性:服务器端规定的字段名和客户端的字段名称保持一致
python服务端:
- # -*- coding: utf-8 -*-
-
- import json
- import uvicorn
- from fastapi import FastAPI
- from pydantic import BaseModel
- from fastapi.middleware.cors import CORSMiddleware
-
- # 创建数据模型
- class Item(BaseModel):
- name: str
- age: int
-
- app = FastAPI()
-
- # 后台api允许跨域
- app.add_middleware(
- CORSMiddleware,
- allow_origins=["*"],
- allow_credentials=True,
- allow_methods=["*"],
- allow_headers=["*"],
- )
-
-
- @app.get("/demo")
- async def root():
- return 'Hello World!'
-
-
- @app.post("/demo")
- async def fcao_predict(item: Item):
- item_dict = item.dict()
- print(item)
- if item.name:
-
- item_dict.update({"name": item.name,
- "age": item.age})
- return item_dict
- # return json.dumps(item_dict)
-
- if __name__ == '__main__':
- uvicorn.run(app=app, host='0.0.0.0', port=5000, debug=True)
客户端:
- <!DOCTYPE html>
- <html lang="en">
-
- <head>
- <meta charset="UTF-8">
- <title>testFastApi</title>
- <script src="./lib/jquery.js"></script>
- </head>
-
- <body>
- <button id="btn">发送请求</button>
- <script>
- params = {
- name: 'abc',
- age: 100
- }
- $('#btn').click(function () {
- $.ajax({ //发送ajax请求
- url: 'http://127.0.0.1:5000/demo',
- type: "post",
- async: true,
- headers: { 'Content-Type': 'application/json;charset=utf8' }, //(在参数都正确的情况下),加上这行防止422错误
- // dataType:"JSON",
- data: JSON.stringify(params),
- success: function (res) {
- // res = JSON.parse(res); //如果以python字典方式返回则不需要进行parse,如果以json方式返回则需要JSON.parse
- console.log(res.name);
- console.log(res)
- alert(res.age);
- },
- error: function () {
- console.log("网络请求错误!");
- }
- });
- });
-
- </script>
- </body>
-
- </html>
需要注意的点:
js解析得到base64有一段前置的base64标识,在python端进行解析的时候需要去掉:
服务端:
- # -*- coding: utf-8 -*-
-
- import json
- import cv2
- import base64
- import numpy as np
- import uvicorn
- from fastapi import FastAPI
- from pydantic import BaseModel
- from fastapi.middleware.cors import CORSMiddleware
-
-
- def img2str(cv_img):
- retval, buffer = cv2.imencode('.png', cv_img)
- pic_str = base64.b64encode(buffer)
- pic_str = pic_str.decode()
- return pic_str
-
- def str2img(pic_str):
- img_data = base64.b64decode(pic_str)
- nparr = np.frombuffer(img_data, np.uint8)
- img_np = cv2.imdecode(nparr, cv2.IMREAD_COLOR)
- return img_np
-
- # 创建数据模型
- class Item(BaseModel):
- data: str
-
- app = FastAPI()
-
-
- # 后台api允许跨域
- app.add_middleware(
- CORSMiddleware,
- allow_origins=["*"],
- allow_credentials=True,
- allow_methods=["*"],
- allow_headers=["*"],
- )
-
-
- @app.get("/bs64")
- async def root():
- return 'Hello World!'
-
- @app.post("/bs64")
- async def fcao_predict(item: Item):
- # print(item)
- # item_dict = item.dict()
- # print(item)
-
-
- if item.data:
- print(item.data[0:100])
- img_np = str2img(item.data.split('base64,')[1])
- # cv2.imshow('img',img_np)
-
- str_img = img2str(img_np)
- print("success")
-
- # cv2.waitKey(0)
- res = json.dumps({"img": str_img})
- return res
-
- if __name__ == '__main__':
- uvicorn.run(app=app,host='0.0.0.0', port=5000,debug=True)
客户端:
- <!DOCTYPE html>
- <html lang="en">
-
- <head>
- <meta charset="UTF-8">
- <meta http-equiv="X-UA-Compatible" content="IE=edge">
- <meta name="viewport" content="width=device-width, initial-scale=1.0">
- <title>Document</title>
- </head>
-
- <body>
- <input type="file" id="Image" name="Image" />
- <button onclick="sent()">sent</button>
- <script type="text/javascript" src="lib/jquery.js"></script>
- <script type="text/javascript">
-
- // 校验上传图片的格式
- function checkImgType(file) {
- //用文件名name后缀判断文件类型,可用size属性判断文件大小不能超过500k , 前端直接判断的好处,免去服务器的压力。
- if (!/\.(jpg|jpeg|png|GIF|JPG|PNG)$/.test(file.name)) {
- return false;
- } else {
- return true;
- }
- }
-
- function sent() {
- var file = document.getElementById('Image');
- openFile(file);
- }
-
- //获取文件的后缀名
- function getSuffix(file){
- var fileName = file.name;
- //获取最后一个.的位置
- var index= fileName.lastIndexOf(".");
- //获取后缀
- var suffix = fileName.substr(index+1);
- //输出结果
- return suffix
- }
-
- function openFile(file) {
- var file = file.files[0]
-
- var suffix = getSuffix(file)
- alert(suffix)
-
- if (!this.checkImgType(file)) {
- alert('上传的图片类型必须是.jpeg,jpg,png中的一种');
- return;
- } else {
- var reader = new FileReader()
- reader.readAsDataURL(file)
- reader.onload = function (e) {
- var bs64 = e.target.result;
- ajaxUploadBase64File(bs64); //上传文件
-
- }
- }
-
- }
- //使用ajax上传
- function ajaxUploadBase64File(base64Data) {
- var url = "http://localhost:5000/bs64";
- $.ajax({
- url: url,
- type: "post",
- headers: { 'Content-Type': 'application/json;charset=utf8' }, //(在参数都正确的情况下),加上这行防止422错误
-
- data: JSON.stringify({
- data: base64Data
- }),
- success: function (res) {
- // console.log(res.img)
- res = JSON.parse(res)
- console.log(res.img)
- var img = new Image();
- // img.src="data:image/png;base64,"+res.img;
- img.src = "data:image/jpeg;base64," + res.img
-
- document.body.appendChild(img); //在界面中显示图片
-
- },
- error: function () {
- console.log("上传失败");
- }
- });
- };
-
- </script>
-
- </body>
-
- </html>
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。