• python flask框架接受axios发送的图片文件


    前端部分

    axios配置

    主要是一些基础的配置,这里可看可不看,主要的不是这里

    import axios from 'axios';
    let baseURL = '/demo'
    
    // 创建axios实例
    const service = axios.create({
        // axios中请求配置有baseURL选项,表示请求URL公共部分
        baseURL: baseURL,
        // 超时
        timeout: 30000,
        // // 禁用 Cookie 等信息
        // withCredentials: false,
    });
    
    // request拦截器
    service.interceptors.request.use(config => {
        // 避免跨域
        config.headers["Content-Type"] = "application/octet-stream";
        config.headers['Access-Control-Allow-Origin'] = "*";
        // get请求映射params参数
        if (config.method === 'get' && config.params) {
            let url = config.url + '?';
            for (const propName of Object.keys(config.params)) {
                const value = config.params[propName];
                const part = encodeURIComponent(propName) + '='
                if (value !== null && typeof (value) !== "undefined") {
                    if (typeof value === 'object') {
                        for (const key of Object.keys(value)) {
                            let params = propName + '[' + key + ']';
                            const subPart = encodeURIComponent(params) + '='
                            url += subPart + encodeURIComponent(value[key]) + "&";
                        }
                    } else {
                        url += part + encodeURIComponent(value) + "&";
                    }
                }
            }
            url = url.slice(0, -1);
            config.params = {};
            config.url = url;
        }
        return config
    }, error => {
        console.log(error)
        Promise.reject(error)
    })
    
    export default service;
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • 40
    • 41
    • 42
    • 43
    • 44
    • 45
    • 46
    • 47

    请求部分代码

    最主要的是一个这部分

    headers: {
                'Content-Type': 'multipart/form-data'
            },
    
    • 1
    • 2
    • 3
    import request from "@/utils/request";
    
    export function predictSingleImage(data) {
        return request({
            url: '/predictSingle',
            headers: {
                'Content-Type': 'multipart/form-data'
            },
            method: 'post',
            data: data,
        });
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12

    页面代码

    主要是要将获得的文件包装秤FormData()
    重要代码就是
    let sendData = new FormData()
    其中的this.predictForm.file就是获取到的文件

    sendData.append(“image”,this.predictForm.file)
    这里的"image"需要和后端代码对应上

    下面是发起请求的代码

    //提交单张图片
        submitSingleImage() {
          let sendData = new FormData();
          sendData.append("image", this.predictForm.file);
          predictSingleImage(sendData).then(res => {
            let response = res.data.result[0];
            //找到response中的最大值即其索引
            let max = response[0];
            let maxIndex = 0;
            for (let i = 1; i < response.length; i++) {
              if (response[i] > max) {
                maxIndex = i;
                max = response[i];
              }
            }
            this.$modal.msgSuccess("预测成功,预测结果为:" + maxIndex);
          }).catch(err => {
            this.$modal.msgError("预测失败" + err);
          })
        },
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20

    这里是获取文件的代码

    
                  
                    
                  
                  
    
    //这里是methods方法
        //打开文件选择框
        openFile() {
          document.getElementById("open").click();
        },
        //选择文件后,将文件信息存入predictForm
        changeFile() {
          const fu = document.getElementById("open");
          if (fu == null) return;
          //如果文件类型不是图片,则返回
          if (!/image\/\w+/.test(fu.files[0].type)) {
            this.$modal.msgWarning("请确保文件为图像类型");
            return false;
          }
          this.predictForm.file = fu.files[0];
          this.predictForm.filename = fu.files[0].name;
          this.predictForm.fileUrl = window.URL.createObjectURL(this.predictForm.file);
        },
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27

    后端代码

    重要的是image = request.files[‘image’].read()
    这里需要跟上面的“image”对应上

    @demo.route('/predictSingle', methods=['POST'])
    def predict_single():
        image = request.files['image'].read()
        image = Image.open(io.BytesIO(image))
        image = preprocess(image)
        output = demo_model(image)
        return jsonify({'result': output.detach().numpy().tolist()})
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7

    结果

    在这里插入图片描述

    在这里插入图片描述
    在这里插入图片描述

  • 相关阅读:
    UE学习记录07----C++中使用事件委托
    (数据科学学习手札139)geopandas 0.11版本重要新特性一览
    Maven 查看项目中的依赖
    C++_linux下_非阻塞键盘控制_程序暂停和继续
    HTML5与CSS3学习笔记【第十一章 用CSS进行布局(二)】
    Git常见命令快速参考
    【开发语言】C语言与Python的互操作详解
    电石双向无人值守称重系统功能详解
    yolov作者简介
    C#通过中序遍历对二叉树进行线索化
  • 原文地址:https://blog.csdn.net/Leezed525/article/details/132900038