无法在 Flask 后端提取 React 前端上传的图像文件

2024-04-24

我正在尝试将图像文件(驻留在本地)从我的反应单页前端应用程序发送到我的烧瓶后端。我尝试过但不限于捕获我的内容类型并在前端指示 encType 的一些事情。尽管如此,post请求表明它是成功的。但是,当我记录 requests.files、request.form、request.values 时,我没有收到任何数据输入。显然,我错过了一些东西,并且确实可以从任何人那里得到任何帮助。谢谢

前端:

import React, { Component } from 'react';
import axios from 'axios';
import logo from './logo.svg';
import './App.css';
// const qs = require('querystring');

class App extends Component {
  constructor(props){
    super();
    this.state = { imagePreviewUrl: '', file: '' };

    this._handleSubmit = this._handleSubmit.bind(this);
    this._handleImageChange = this._handleImageChange.bind(this);
    this.uploadImage = this.uploadImage.bind(this);
  }

  _handleImageChange(e){
    e.preventDefault();
    let file = e.target.files[0];
    let reader = new FileReader();
    reader.onloadend = () => {
      this.setState({ file: file,
                      imagePreviewUrl: reader.result });
    }
    reader.readAsDataURL(file);
  }

  _handleSubmit(e){
    e.preventDefault();
    console.log("file value before this.uploadImage call:",this.state.file);
    this.uploadImage(this.state.file);

  }

  uploadImage(filepath){

      let imageFormData = new FormData();
      imageFormData.append('filepath', filepath, filepath.name);
      let newHeaders = new Headers({
              "Content-type": "image/png"
            });
      console.log("checking if imageFormData has value:",imageFormData.has('filepath'));
        return axios.post('/add', newHeaders, imageFormData)
          .then((response) => {
            console.log("response:", response);
          })
          .catch((err) => {
            console.log("error:", err);
          });

    }


  render() {

    let { imagePreviewUrl } = this.state;
    let $imagePreview = null
    if (imagePreviewUrl){
      $imagePreview = ( <img src={imagePreviewUrl} />);
    }
    else {
      $imagePreview = (<div className="previewText">Please select an Image for Preview</div>);
    }
    return (
      <div className="App">
        <div className="App-header">
          <img src={logo} className="App-logo" alt="logo" />
          <h2>Welcome to React</h2>
        </div>
        <form onSubmit={this._handleSubmit}>
          <div>
            <label htmlFor="image_uploads">Choose images to upload (PNG, JPG)</label>
            <input type="file" id="image_uploads" name="filepath" encType="multipart/form-data" onChange={this._handleImageChange}/>
          </div>
          <div>
            <button type='submit'>Submit</button>
          </div>
        </form>
        <div>
        {$imagePreview}
        </div>
      </div>
    );
  }
}

export default App;

Backend:

from flask import Flask, request, render_template, send_from_directory

gunicorn_error_logger = logging.getLogger('gunicorn.error')
app.logger.handlers.extend(gunicorn_error_logger.handlers)
app.logger.setLevel(logging.DEBUG)
app = Flask(__name__)


@app.route('/', methods=['GET'])
def root():
    app.logger.debug("Inside root route")
    return render_template('index.html')

@app.route('/add', methods=['POST'])
def add_handler():
    app.logger.debug("Inside add route")
    app.logger.debug("Request Params: {}".format(request))
    app.logger.debug("Values: {}".format(request.values))
    app.logger.debug("Form: {}".format(request.form))
    app.logger.debug("Files: {}".format(request.files))

    return "got it"

我在尝试向服务器发送声音 blob 时遇到了同样的问题。数据接收到,调用可以看到request.get_data()如果您仅根据请求调用此方法(请参阅:https://stackoverflow.com/a/23898949/1058203 https://stackoverflow.com/a/23898949/1058203)。 但是,我发现没有简单的方法来正确解析这些数据。 什么对我有用:

首先在客户端将 blob 转换为 base64,然后以 Json 形式发送到服务器:

var reader = new FileReader();
reader.readAsDataURL(blob); 
reader.onloadend = function() {
  var base64audio = reader.result;
  // may not apply or differ in your case
  var prefixToDrop = 'data:audio/wav;base64,';
  var base64audioCut = base64audio.substring(prefixToDrop.length);
  callbackFn(base64audioCut)
};

使用 JQuery 在回调中发送到后端:

$.ajax({
        type: 'POST',
        url: '/receiveAudio',
        data: JSON.stringify({
          "type": "wav",
          "base64audio" : base64audioCut
        }),
        dataType:"json",
        processData: false,
        contentType: "application/json;",
        success: function(x){...},
        error: function(x){...},
        processData: false
});

后端:

@app.route('/receiveAudio', methods=['POST'])
def receiveAudio():
    dataKey = 'base64audio'
    json = request.get_json()

    if not dataKey in json:
        return abort(400, "Missing 'base64audio' key")

    base64_decoded = base64.b64decode(json[dataKey])
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

无法在 Flask 后端提取 React 前端上传的图像文件 的相关文章

  • mod_wsgi 下的 psp(python 服务器页面)代码?

    有没有办法在 apache mod wsgi 下运行 psp python 服务器页面 代码 虽然我们正在转向基于 wsgi 的新框架 但我们仍然有一些用 psp 编写的遗留代码 这些代码在 mod python 下运行 我们希望能够在托管
  • jinja2.exceptions.TemplateNotFound:index.html

    我尝试使用 Flask 打开 index html run py from app import app app run debug True init py from flask import Flask app Flask name f
  • 如何在多个端口上运行 FastAPI 应用程序?

    我有一个 FastAPI 应用程序 正在使用 Uvicorn 以编程方式在端口 30000 上运行 现在我也想在端口 8443 上运行相同的应用程序 相同的应用程序需要在这两个端口上运行 我怎样才能在Python代码中做到这一点 最小可重现
  • 在 Python 3.5 64 位上通过 pip 安装 OpenCV

    我尝试安装 OpenCV 但找不到任何合适的 pip 软件包 我决定上网查找有关如何安装它的官方文档 并发现this https opencv python tutroals readthedocs io en latest py tuto
  • Python,将CSV文件转换为SQL表

    我有一个没有标题的 CSV 文件 并尝试从文件中的某些列创建 SQL 表 我尝试了这里给出的解决方案 使用 Python 将 CSV 文件导入 sqlite3 数据库表 https stackoverflow com questions 2
  • python 2.7 字符 \u2013 [重复]

    这个问题在这里已经有答案了 我有以下代码 coding utf 8 print u William Burges 1827 81 was an English architect and designer 当我尝试从cmd运行它时 我收到以
  • 使用另一个索引数组正确索引多维 Numpy 数组

    我正在尝试索引多维数组P与另一个数组indices 它指定我想要沿最后一个轴的哪个元素 如下所示 import numpy as np M N 20 10 P np random rand M N 2 9 index into the la
  • 将numpy字符串数组转换为int数组[重复]

    这个问题在这里已经有答案了 我有一个 numpy ndarray a 0 99 0 56 0 56 2 02 0 96 如何将其转换为int 输出 a 0 99 0 0 0 56 0 56 2 02 0 96 我想要 0 0 代替空白 im
  • Pymacs 助手在 30 秒后未启动

    我见过其他关于此的问题 但没有一个得到真正的回答 而且没有一个是我的问题 我有一个新系统 emacs 23 1 Centos 6 2 我认为 我下载了最新的 pymacs 并安装了它 但是 我得到 error Pymacs helper d
  • scikit-learn - 具有置信区间的 ROC 曲线

    我可以使用 ROC 曲线scikit learn with fpr tpr thresholds metrics roc curve y true y pred pos label 1 where y true是基于我的黄金标准的值列表 即
  • 将 Pandas 列转换为日期时间

    我在 pandas DataFrame 中有一个字段以字符串格式导入 它应该是一个日期时间变量 如何将其转换为日期时间列 然后根据日期进行过滤 Example raw data pd DataFrame Mycol 05SEP2014 00
  • 使用请求和多处理时的奇怪问题

    请检查这个Python代码 usr bin env python import requests import multiprocessing from time import sleep time from requests import
  • 您忽略了哪些 PEP 8 准则,哪些是您坚持的? [关闭]

    Closed 这个问题是基于意见的 help closed questions 目前不接受答案 多年来 我编写的 Python 越多 我就越发现自己同意大多数准则 尽管我出于自己的原因始终有意地违反了一些准则 我很想知道 PEP 8 也可能
  • 如何找到运行代码的 conda 环境的名称?

    我正在寻找一种好方法来从正在运行的代码或交互式 python 实例中找出我所在的 conda 环境的名称 用例是我通过 miniconda 安装运行带有 Python 2 和 Python 3 内核的 Jupyter 笔记本 默认环境是Py
  • 如何解析代码(Python)?

    我需要解析一些特殊的数据结构 它们采用某种类似 C 的格式 大致如下所示 Group GroupName C Style comment Group AnotherGroupName Entry some variables 0 3 141
  • 抑制来自 python pandas 描述的名称 dtype

    可以说我有 r pd DataFrame A 1 B pd Series 1 index list range 4 dtype float32 And r B describe mean std min max 给出输出 mean 1 0
  • Pytest - 如何将参数传递给 setup_class?

    我有一些代码 如下所示 我得到了too few args当我运行它时出错 我没有打电话setup class明确地 所以不确定如何向它传递任何参数 我尝试用以下方法装饰该方法 classmethod 但仍然看到相同的错误 我看到的错误是这样
  • python:Windows终端中的unicode,使用的编码?

    我在 Windows 7 终端中使用 Python 解释器 我正在尝试了解 unicode 和编码 I type gt gt gt s gt gt gt s x89 gt gt gt u u gt gt gt u u xeb 问题1 字符串
  • numpy 沿第一个轴添加

    我想通过简单地沿第一个轴执行相同的加法来添加两个具有不同维度的数组 非矢量化解决方案 x np array 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 shape 4 3 2 y np a
  • Python 用 lambda 函数封闭作用域变量

    我写了这个简单的代码 def makelist L for i in range 5 L append lambda x i x return L 好的 现在我打电话 mylist makelist 因为稍后调用嵌套函数时会查找封闭范围变量

随机推荐