React Native,从 Axios 发送图像但在 Multer Express JS 上未接收

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

我无法在 Express js 服务器上接收从 axios/react native 发送的图像。当我从 Postman/ThunderClient 向服务器发送相同的请求时,它工作正常。

这是我在 React Native 中使用的代码。

const pickImage = async () => {
    let result = await ImagePicker.launchImageLibraryAsync({
      mediaTypes: ImagePicker.MediaTypeOptions.Images,
      allowsEditing: true,
      aspect: [4, 3],
      quality: 1,
    });

    if (!result.canceled) {
      setImage(result.assets[0]);
    }
  };

  const createFormData = async (body: any = {}) => {
    const data = new FormData();

    if (image) {
      const response = await fetch(image.uri || "");
      const blob = await response.blob();

      data.append("image", blob, "profile.jpg");
    }

    Object.keys(body).forEach((key) => {
      data.append(key, body[key]);
    });

    console.log(blob);

    return data;
  };

  const uploadImage = async (id: string, access_token: string) => {
    const body = await createFormData({ id });
    const response = await axios.post(
      `${API_BASE_URL}user/validate/upload-profile-image`,
      body,
      {
        headers: {
          Authorization: `Bearer ${access_token}`,
        },
        transformRequest: [(data) => body],
        validateStatus: function (status) {
          return status < 500;
        },
      }
    );

    return response;
  };

这是我在控制台日志记录 blob 上得到的信息 - {"_parts": [["image", [Blob]], ["id", "af1ee491-61c9-4368-93ef-813256b041dc"]]}

我已经尝试了一切,但似乎没有任何作用。任何建议表示赞赏。

谢谢。

react-native express axios multer expo-image-picker
1个回答
0
投票

使用expo文件系统的UploadAsync方法解决了这个问题。

const options: FileSystem.FileSystemUploadOptions = {
  headers: {
    "Content-Type": "multipart/form-data",
    Accept: "image/jpeg, image/png",
  },
  httpMethod: "POST",
  uploadType: FileSystem.FileSystemUploadType.MULTIPART,
  fieldName: "image",
  parameters: {
    id,
  },
};

const response = await FileSystem.uploadAsync(
  `${API_BASE_URL}user/validate/upload-profile-image`,
  image?.uri || "",
  options
);
© www.soinside.com 2019 - 2024. All rights reserved.