【问题标题】:How to send image files from a localhost React Native app to a localhost Flask API如何将图像文件从 localhost React Native 应用程序发送到 localhost Flask API
【发布时间】:2021-06-15 20:43:51
【问题描述】:

我在我的 React Native 应用程序中使用 ImagePicker:https://www.npmjs.com/package/react-native-image-picker 来拍照或选择图像,然后我想将该图像发送到 Flask API。由于某种原因,我根本不知道该怎么做。

这是获取图像并将所有内容发送到 Flask API 的代码

const [image, setImage] = useState(null);

               ...

 const pickImage = async () => {
      let result = await ImagePicker.launchImageLibraryAsync({
      mediaTypes: ImagePicker.MediaTypeOptions.All,
      allowsEditing: true,
      aspect: [4, 3],
      quality: 1,
      });
      console.log(result);
      if (!result.cancelled) {
        setImage(result);
      }

    };

    const takeImage = async () => {
      let result = await ImagePicker.launchCameraAsync({
      mediaTypes: ImagePicker.MediaTypeOptions.All,
      allowsEditing: true,
      aspect: [4, 3],
      quality: 1,
      });
      console.log(result);
      if (!result.cancelled) {
      setImage(result);
      }
    };

    //POST a new form to the database
    const postForm = async () =>{
      // const photoData = new FormData();
      //   photoData.append('file', image[0]);
      //   photoData.append('filename', image.fileName.value);

      fetch('http://10.0.2.2:5000/forms', {
        method: 'POST',
        headers: {
          'Accept': 'application/json',
          'Content-Type': 'application/json',
        },
        body: JSON.stringify({
          Name: Name,
          Phone: Phone,
          Email: Email,
          County: selectedValue,
          RoadName: RoadName,
          MileMarker: MileMarker,
          Comments: Comments,
          Path: "",
          Image: image
        })
      }).then(response =>{
        if(response.ok){
          return response.json();
        }
      }).then(data => console.log(data));
    }


我尝试仅发送变量“路径”中的图像 URI。然而,这最终不会成为 Flask 中的图像,只是一个字符串(这是有道理的)。然后我尝试发送 ImagePicker 给我的图像(如您现在所见),这也不起作用。 Flask 不喜欢 Image 变量,我对此并不感到惊讶。

FLask API:

def post(self):
        json_data = request.get_json()

        #Create a new Form using Marshmallow
        new_form = Forms(
            Name=request.json['Name'],
            Phone=request.json['Phone'],
            Email=request.json['Email'],
            County=request.json['County'],
            RoadName=request.json['RoadName'],
            MileMarker=request.json['MileMarker'],
            Comments=request.json['Comments'],
            Path=request.json['Path'],
            Image=request.json['Image']
        )
        db.session.add(new_form)
        db.session.commit()

        return form_schema.dump(new_form)

错误信息很大,但这是它的底部:

    return DBAPIBinary(value)
sqlalchemy.exc.StatementError: (builtins.TypeError) 'str' object cannot be interpreted as an integer
[SQL: INSERT INTO [ComplaintForms] ([Name], [Phone], [Email], [County], [RoadName], [MileMarker], [Comments], [Path], [Image]) OUTPUT inserted.[ID] VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)]
[parameters: [{'Name': 'Esri', 'Path': '', 'Comments': 'sdf', 'Phone': '5557778888', 'Image': {'cancelled': False, 'type': 'image', 'uri': 'file:///data/user/0/host.exp.exponent/cache/ExperienceData/UNVERIFIED-10.69.69.8-DOH_Mobile_V1/ImagePicker/1d899dd8-86ac-407b-8345-b3514e573144.jpg', 'width': 1396, 'height': 1047}, 'RoadName': 'big boy rda', 'Email': 'asdf', 'County': None, 'MileMarker': None}]]
127.0.0.1 - - [15/Jun/2021 16:37:38] "POST /forms HTTP/1.1" 500 -

您是如何做到这一点的?如果这是一个广泛的问题,我深表歉意,但我已经坚持了一个月。如果您需要更多信息,请询问,我会尽力提供。

【问题讨论】:

    标签: python react-native flask react-native-image-picker


    【解决方案1】:

    您的一个表单字段实际上从前端接受值str 而不是int。您需要仔细检查表格列属性与传入值。

    我不知道您使用了哪一列int,但在您的表中提供了str 值,但快速猜测是Phone 列,在您的表中应该是str 而不是@987654327 @。

    如果它是任何其他字段应该是int,但因为前端字段的默认类型始终是str,你应该像这样在你的后端进行解析,

    int_value = int(request.json['ShouldBeIntField'])
    

    但是当它引发 ValueError 时需要额外的错误,以防它无法将其转换为整数。

    【讨论】:

    • 谢谢你,但问题的主要原因是关于如何将图像文件从 React 发送到 Flask,如标题所示。错误消息只是显示了当我尝试我的代码时发生的事情,我怀疑这无论如何都是不正确的方法。如果这有点令人困惑,我很抱歉。我实际上已经解决了你指出的问题。但它并没有让我更接近。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2023-03-09
    • 2020-05-24
    • 2023-03-03
    • 2021-07-24
    • 2019-02-19
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多