我无法查看我上传到mongodb的个人资料图片

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

我是 React Native 的新手,但我正在尝试在 MERN 堆栈上提高自己。从前端,通过 expo-image-picker,我可以通过 Multer 将照片作为用户模式中的 profilePicture 字符串保存到 MongoDB。但是,当我想使用 Axios 获取用户信息时,即使用户信息以 String 形式出现,我也看不到 中的图像。

import axios from "axios";

export default function UploadImage() {
  const [image, setImage] = useState("");

  const getUser = async () => {
    const res = await axios.get("http://192.168.1.112:3000/api/users/profile");
    console.log(res.data.profilePicture);
    setImage(res.data.profilePicture);
  };

  useEffect(() => {
    getUser();
  }, []);

  const addImage = async () => {
    try {
      const { status } =
        await ImagePicker.requestMediaLibraryPermissionsAsync();
      if (status !== "granted") {
        alert("Sorry, we need camera roll permissions to make this work!");
        return;
      } else {
        let _image = await ImagePicker.launchImageLibraryAsync({
          mediaTypes: ImagePicker.MediaTypeOptions.All,
          allowsEditing: true,
          aspect: [4, 3],
          quality: 1,


        });
        console.log(JSON.stringify(_image));
        if (!_image.cancelled) {
          const uri = _image.assets[0].uri;
          console.log(uri);
          uploadImage(uri);
          setImage(uri);
        }
      }
    } catch (error) {
      console.log(error);
    }
  };

  const uploadImage = async (uri) => {

    let formData = new FormData();
    formData.append("profilePicture", {
      uri: uri,
      name: "profilePicture.jpg",
      type: "image/png",
    });

    try {

      let response = await axios.post(
        "http://192.168.1.112:3000/upload-profile-picture/",
        formData,
        {
          headers: {
            Accept: "application/json",
            "Content-Type": "multipart/form-data",
          },
        }
      );
      console.log(response.data);
    } catch (error) {
      console.error(error);
    }
  };

  return (
    <View style={{ flexDirection: "row" }}>
      <View style={imageUploaderStyles.container}>
        {image && (
          <Image source={{ uri: image }} style={{ width: 200, height: 200 }} />
        )}

        <View style={imageUploaderStyles.uploadBtnContainer}>
          <TouchableOpacity
            onPress={addImage}
            style={imageUploaderStyles.uploadBtn}
          >
            <AntDesign name="camera" size={20} color="white" />
          </TouchableOpacity>
        </View>
      </View>
    </View>
  );
}
react-native mern multer expo-image-picker
1个回答
0
投票

首先检查网址是否正确,您可以尝试使用

<FastImage/>
而不是常规
Image
标签,因为使用快速图像可以更好地处理网络图像。以下是更多详细信息的文档:https://www.npmjs.com/package/react-native-fast-image

如果您仍然面临困难,请告诉我

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