React Native 使用 axios 和 expo 图像选择器上传图像

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

我正在尝试使用 expo 图像选择器和 axios 上传图像。

这是我的代码:


// Select image from Library <--comment
  const selectImage = async () => {
    // Get iamge
    try {
      // Check has library permission <--comment
      const hasLibraryPermission = await requestLibraryPermision();
      if (hasLibraryPermission) {
        // Lunch camers <--comment
        const result = await ImagePicker.launchCameraAsync();

        // Check is canceld or not <--comment
        if (!result.canceled) {
          // Set result uri to state <--comment
          const newInformation = { ...information };
          newInformation.data.image = result.assets[0].uri;
          setInformation(newInformation);

          // Define and append result to form data <--comment
          const formData = new FormData();
          formData.append("image", result.assets[0]);

          // Define request url <--comment
          const url = `${serverData.url}/profile/update-image`;

          // Send post upload image request <--comment
          await axios
            .post(url, formData, {
              headers: {
                "content-type": "multipart/form-data",
              },
            })
            .then((response) => {
              console.log("response: ", response.data);
            })
            .catch((error) => {
              console.log("CATCH ERROR: ", error);
            });
        }
      }
    } catch (error) {
      console.log("Error: ", error);
    }
  };

请求显示此错误日志:

CATCH ERROR:  [AxiosError: Network Error]
我在网上搜索,甚至向吟游诗人和聊天 gpt ai 询问,但他们无法回答我,有什么问题吗?

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

文件对象应该具有

uri
name
type
字段,如下所示:

const formData = new FormData();
formData.append(
  'image',
  {
    uri: result.assets[0].uri,
    name: <name>,
    type: <type>
  }
);
axios.post(<url>, formData);
© www.soinside.com 2019 - 2024. All rights reserved.