FastApi和Jquery传输图片

一、FastApi与Ajax的网络通信

需要注意的点:

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>

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

需要注意的点:

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>
  • 0
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
jQuery是一个JavaScript库,可以非常方便地处理图片上传和删除。以下是一个简单的示例代码: HTML代码: ``` <form id="upload-form" action="upload.php" method="post" enctype="multipart/form-data"> <input type="file" name="image" id="image"> <button type="submit" id="upload-btn">上传</button> </form> <div id="image-container"></div> ``` jQuery代码: ``` $(document).ready(function() { // 上传图片 $('#upload-form').submit(function(event) { event.preventDefault(); // 防止表单提交 var formData = new FormData($(this)[0]); $.ajax({ url: $(this).attr('action'), type: $(this).attr('method'), data: formData, dataType: 'json', processData: false, contentType: false, success: function(response) { $('#image-container').append('<img src="' + response.image_url + '">'); } }); }); // 删除图片 $(document).on('click', '.delete-btn', function() { var imageId = $(this).data('image-id'); $.ajax({ url: 'delete.php', type: 'post', data: {id: imageId}, dataType: 'json', success: function(response) { if (response.success) { $('#image-' + imageId).remove(); } } }); }); }); ``` 在上面的示例中,我们使用了jQuery的`$.ajax()`方法来进行异步上传和删除图片。当用户上传图片时,我们使用`FormData`对象来构建表单数据,并将其用作`data`选项。我们还使用`processData`和`contentType`选项来防止jQuery将表单数据转换为字符串类型。 在上传成功后,我们向`#image-container`元素添加一个新的图片标签,其`src`属性为所上传图片的URL。对于删除图片,我们使用`data`属性来传递要删除的图片ID,然后从DOM中删除该图片。 需要注意的是,这只是一个简单的示例,实际上还需要进行安全性检查和错误处理等操作。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值