• FastApi和Ajax传输图片


    一、FastApi与Ajax的网络通信

    需要注意的点:

    1.跨域问题:在fastapi中设置即可(见代码)

    2.字段一致性:服务器端规定的字段名和客户端的字段名称保持一致

    python服务端

    1. # -*- coding: utf-8 -*-
    2. import json
    3. import uvicorn
    4. from fastapi import FastAPI
    5. from pydantic import BaseModel
    6. from fastapi.middleware.cors import CORSMiddleware
    7. # 创建数据模型
    8. class Item(BaseModel):
    9. name: str
    10. age: int
    11. app = FastAPI()
    12. # 后台api允许跨域
    13. app.add_middleware(
    14. CORSMiddleware,
    15. allow_origins=["*"],
    16. allow_credentials=True,
    17. allow_methods=["*"],
    18. allow_headers=["*"],
    19. )
    20. @app.get("/demo")
    21. async def root():
    22. return 'Hello World!'
    23. @app.post("/demo")
    24. async def fcao_predict(item: Item):
    25. item_dict = item.dict()
    26. print(item)
    27. if item.name:
    28. item_dict.update({"name": item.name,
    29. "age": item.age})
    30. return item_dict
    31. # return json.dumps(item_dict)
    32. if __name__ == '__main__':
    33. uvicorn.run(app=app, host='0.0.0.0', port=5000, debug=True)

    客户端:

    1. html>
    2. <html lang="en">
    3. <head>
    4. <meta charset="UTF-8">
    5. <title>testFastApititle>
    6. <script src="./lib/jquery.js">script>
    7. head>
    8. <body>
    9. <button id="btn">发送请求button>
    10. <script>
    11. params = {
    12. name: 'abc',
    13. age: 100
    14. }
    15. $('#btn').click(function () {
    16. $.ajax({ //发送ajax请求
    17. url: 'http://127.0.0.1:5000/demo',
    18. type: "post",
    19. async: true,
    20. headers: { 'Content-Type': 'application/json;charset=utf8' }, //(在参数都正确的情况下),加上这行防止422错误
    21. // dataType:"JSON",
    22. data: JSON.stringify(params),
    23. success: function (res) {
    24. // res = JSON.parse(res); //如果以python字典方式返回则不需要进行parse,如果以json方式返回则需要JSON.parse
    25. console.log(res.name);
    26. console.log(res)
    27. alert(res.age);
    28. },
    29. error: function () {
    30. console.log("网络请求错误!");
    31. }
    32. });
    33. });
    34. script>
    35. body>
    36. html>

    二、FastApi与Ajax通过Base64传输图片

    需要注意的点:

    js解析得到base64有一段前置的base64标识,在python端进行解析的时候需要去掉:

     服务端

    1. # -*- coding: utf-8 -*-
    2. import json
    3. import cv2
    4. import base64
    5. import numpy as np
    6. import uvicorn
    7. from fastapi import FastAPI
    8. from pydantic import BaseModel
    9. from fastapi.middleware.cors import CORSMiddleware
    10. def img2str(cv_img):
    11. retval, buffer = cv2.imencode('.png', cv_img)
    12. pic_str = base64.b64encode(buffer)
    13. pic_str = pic_str.decode()
    14. return pic_str
    15. def str2img(pic_str):
    16. img_data = base64.b64decode(pic_str)
    17. nparr = np.frombuffer(img_data, np.uint8)
    18. img_np = cv2.imdecode(nparr, cv2.IMREAD_COLOR)
    19. return img_np
    20. # 创建数据模型
    21. class Item(BaseModel):
    22. data: str
    23. app = FastAPI()
    24. # 后台api允许跨域
    25. app.add_middleware(
    26. CORSMiddleware,
    27. allow_origins=["*"],
    28. allow_credentials=True,
    29. allow_methods=["*"],
    30. allow_headers=["*"],
    31. )
    32. @app.get("/bs64")
    33. async def root():
    34. return 'Hello World!'
    35. @app.post("/bs64")
    36. async def fcao_predict(item: Item):
    37. # print(item)
    38. # item_dict = item.dict()
    39. # print(item)
    40. if item.data:
    41. print(item.data[0:100])
    42. img_np = str2img(item.data.split('base64,')[1])
    43. # cv2.imshow('img',img_np)
    44. str_img = img2str(img_np)
    45. print("success")
    46. # cv2.waitKey(0)
    47. res = json.dumps({"img": str_img})
    48. return res
    49. if __name__ == '__main__':
    50. uvicorn.run(app=app,host='0.0.0.0', port=5000,debug=True)

     客户端:

    1. html>
    2. <html lang="en">
    3. <head>
    4. <meta charset="UTF-8">
    5. <meta http-equiv="X-UA-Compatible" content="IE=edge">
    6. <meta name="viewport" content="width=device-width, initial-scale=1.0">
    7. <title>Documenttitle>
    8. head>
    9. <body>
    10. <input type="file" id="Image" name="Image" />
    11. <button onclick="sent()">sentbutton>
    12. <script type="text/javascript" src="lib/jquery.js">script>
    13. <script type="text/javascript">
    14. // 校验上传图片的格式
    15. function checkImgType(file) {
    16. //用文件名name后缀判断文件类型,可用size属性判断文件大小不能超过500k , 前端直接判断的好处,免去服务器的压力。
    17. if (!/\.(jpg|jpeg|png|GIF|JPG|PNG)$/.test(file.name)) {
    18. return false;
    19. } else {
    20. return true;
    21. }
    22. }
    23. function sent() {
    24. var file = document.getElementById('Image');
    25. openFile(file);
    26. }
    27. //获取文件的后缀名
    28. function getSuffix(file){
    29. var fileName = file.name;
    30. //获取最后一个.的位置
    31. var index= fileName.lastIndexOf(".");
    32. //获取后缀
    33. var suffix = fileName.substr(index+1);
    34. //输出结果
    35. return suffix
    36. }
    37. function openFile(file) {
    38. var file = file.files[0]
    39. var suffix = getSuffix(file)
    40. alert(suffix)
    41. if (!this.checkImgType(file)) {
    42. alert('上传的图片类型必须是.jpeg,jpg,png中的一种');
    43. return;
    44. } else {
    45. var reader = new FileReader()
    46. reader.readAsDataURL(file)
    47. reader.onload = function (e) {
    48. var bs64 = e.target.result;
    49. ajaxUploadBase64File(bs64); //上传文件
    50. }
    51. }
    52. }
    53. //使用ajax上传
    54. function ajaxUploadBase64File(base64Data) {
    55. var url = "http://localhost:5000/bs64";
    56. $.ajax({
    57. url: url,
    58. type: "post",
    59. headers: { 'Content-Type': 'application/json;charset=utf8' }, //(在参数都正确的情况下),加上这行防止422错误
    60. data: JSON.stringify({
    61. data: base64Data
    62. }),
    63. success: function (res) {
    64. // console.log(res.img)
    65. res = JSON.parse(res)
    66. console.log(res.img)
    67. var img = new Image();
    68. // img.src="data:image/png;base64,"+res.img;
    69. img.src = "data:image/jpeg;base64," + res.img
    70. document.body.appendChild(img); //在界面中显示图片
    71. },
    72. error: function () {
    73. console.log("上传失败");
    74. }
    75. });
    76. };
    77. script>
    78. body>
    79. html>
  • 相关阅读:
    Java——》线程的打断(停止正在运行的线程)
    虚拟机改IP地址
    Java NIO :如何为通道注册多个事件及多线程处理 Accetp 请求
    Mysql通用日志(general)文件太大,如何定期清理与备份
    如何在 Wio Terminal 上运行 RT-Thread 操作系统
    element-ui封装loading,便于在拦截请求或其他场景使用
    vs调试技巧(详细)
    Gin学习记录4——Controller和中间件
    【linux】SourceForge 开源软件开发平台和仓库
    Java版本+企业电子招投标系统源代码+支持二开+招投标系统+中小型企业采购供应商招投标平台
  • 原文地址:https://blog.csdn.net/ssunshining/article/details/126694480