使用包含图像的 FormData 响应本机 HTTP 请求

问题描述 投票:0回答:1

我的目标是将照片从本地设备发送到服务器。

我使用

import { launchImageLibrary } from "react-native-image-picker";
选择名为
photo
的资源并使用

const resp = await fetch(photo.uri);
const blob = resp.blob();
formData.append('regPhoto', blob);
registerUser(formData);

将其作为 blob 附加到表单数据中。我检查了await fetch 调用返回了200 并带有有意义的数据。然后使用 XMLHttpRequest API 发送此 formData:

function registerUser(formData: FormData) {
  cl("registerUser");
  return new Promise((resolve) => {
    const xhr = new XMLHttpRequest();
    xhr.open("POST", url + "registerUser");
    xhr.onreadystatechange = () => {
      const resObj = onReadyStateChange(xhr);
      if (resObj) {
        resolve(resObj);
      }
    };

    xhr.send(formData);
  });
}

发生了两件事,服务器接收没有图像的请求并处理没有图像的请求。这在某种程度上是成功的。同时,客户端(android 模拟器)有一个 JSON 响应,内容为:无法识别的 formdata 部分。我不确定这实际上是从哪里来的。

有人知道这里发生了什么事吗?只是想通过 formData 将图像上传到我的服务器。

我尝试了其他将照片附加到 formData 的方法,但出现了相同的错误。

javascript node.js typescript react-native
1个回答
0
投票

首先,确保您有一个可供上传的图像文件。通常,您可以使用像react-native-image-picker这样的库从用户的设备获取此图像。

import React, { useState } from 'react';
import { View, Button, Image } from 'react-native';
import * as ImagePicker from 'react-native-image-picker';

const UploadImage = () => {
  const [imageUri, setImageUri] = useState(null);

  const selectImage = () => {
    ImagePicker.launchImageLibrary({ mediaType: 'photo' }, (response) => {
      if (response.didCancel) {
        console.log('User cancelled image picker');
      } else if (response.error) {
        console.log('ImagePicker Error: ', response.error);
      } else {
        setImageUri(response.assets[0].uri);
      }
    });
  };

  const uploadImage = async () => {
    const formData = new FormData();
    formData.append('photo', {
      uri: imageUri,
      name: 'photo.jpg',
      type: 'image/jpeg'
    });

    try {
      const response = await fetch('https://your-api-endpoint.com/upload', {
        method: 'POST',
        body: formData,
        headers: {
          'Content-Type': 'multipart/form-data'
        }
      });
      const result = await response.json();
      console.log(result);
    } catch (error) {
      console.error('Error uploading image: ', error);
    }
  };

  return (
    <View>
      <Button title="Select Image" onPress={selectImage} />
      {imageUri && (
        <View>
          <Image source={{ uri: imageUri }} style={{ width: 100, height: 100 }} />
          <Button title="Upload Image" onPress={uploadImage} />
        </View>
      )}
    </View>
  );
};

export default UploadImage;

npm 安装 axios

纱线添加axios

import React, { useState } from 'react';
import { View, Button, Image } from 'react-native';
import * as ImagePicker from 'react-native-image-picker';
import axios from 'axios';

const UploadImage = () => {
  const [imageUri, setImageUri] = useState(null);

  const selectImage = () => {
    ImagePicker.launchImageLibrary({ mediaType: 'photo' }, (response) => {
      if (response.didCancel) {
        console.log('User cancelled image picker');
      } else if (response.error) {
        console.log('ImagePicker Error: ', response.error);
      } else {
        setImageUri(response.assets[0].uri);
      }
    });
  };

  const uploadImage = async () => {
    const formData = new FormData();
    formData.append('photo', {
      uri: imageUri,
      name: 'photo.jpg',
      type: 'image/jpeg'
    });

    try {
      const response = await axios.post('https://your-api-endpoint.com/upload', formData, {
        headers: {
          'Content-Type': 'multipart/form-data'
        }
      });
      console.log(response.data);
    } catch (error) {
      console.error('Error uploading image: ', error);
    }
  };

  return (
    <View>
      <Button title="Select Image" onPress={selectImage} />
      {imageUri && (
        <View>
          <Image source={{ uri: imageUri }} style={{ width: 100, height: 100 }} />
          <Button title="Upload Image" onPress={uploadImage} />
        </View>
      )}
    </View>
  );
};

export default UploadImage;

© www.soinside.com 2019 - 2024. All rights reserved.