如何将图像文件从localhost React本机应用程序发送到localhost Flask API

2024-09-27 00:14:48 发布

您现在位置:Python中文网/ 问答频道 /正文

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

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

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));
    }


我尝试只发送变量“Path”中的图像URI。然而,这并不是烧瓶中的一个图像,而是一个字符串(这很有意义)。然后,我尝试发送图像,因为它是由ImagePicker提供给我的(正如您现在看到的),这也不起作用。Flask不喜欢Image变量,对此我并不感到惊讶

烧瓶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 -

你到底是怎么做到的?我很抱歉,如果这是一个广泛的问题,但我已经坚持了大约一个月。如果你需要更多的信息,请询问,我会尽力提供


Tags: pathname图像imagejsonnewemailrequest
1条回答
网友
1楼 · 发布于 2024-09-27 00:14:48

其中一个表单字段实际上接受来自前端的值为str,而不是int。您需要仔细检查表列属性和传入值

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

如果任何其他字段都应该是int,但由于前端字段的默认类型始终是str,您应该在后端执行如下解析:

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

但如果无法将其转换为整数,则在引发ValueError时需要额外的错误

相关问题 更多 >

    热门问题