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;

请求部分代码

最主要的是一个这部分

headers: {
            'Content-Type': 'multipart/form-data'
        },
import request from "@/utils/request";

export function predictSingleImage(data) {
    return request({
        url: '/predictSingle',
        headers: {
            'Content-Type': 'multipart/form-data'
        },
        method: 'post',
        data: data,
    });
}

页面代码

主要是要将获得的文件包装秤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);
      })
    },

这里是获取文件的代码

<!-- 前端页面代码 -->
              <el-input placeholder="请选择文件" v-model="predictForm.filename" disabled>
                <template slot="append">
                  <el-button icon="el-icon-folder-opened" @click="openFile">点此上传文件</el-button>
                </template>
              </el-input>
              <input type="file" name="filename" id="open" style="display: none" accept="image/*"
                     @change="changeFile"/>

//这里是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);
    },

后端代码

重要的是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()})

结果

在这里插入图片描述

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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值