Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.2k views
in Technique[技术] by (71.8m points)

expo - Cannot upload file from React Native: "Network request failed"?

When trying to upload a selected image from my React Native project I get a nondescript error message:

Network request failed

Seems to be a common issue, but most people are just forgetting their file types or are on Android and have an issue with Flipper. Nothing that has worked for anyone I've found with the same symptoms has worked for me.

Code:

  const localUri = result.uri;
  const filename = localUri.split("/").pop();

  const type = mime.lookup(localUri) || "image";

  const formData = new FormData();
  formData.append("file", { uri: localUri, name: filename, type });

  try {
    const file = await fetch(`${SERVER_URL}/api/upload`, {
      method: "POST",
      body: formData,
    }).then((res) => {
      console.log(res);
      return res.status === 200 ? res.text() : res.json();
    });
  } catch (e) {
    console.log(e);
  }

Considerations:

  • Using a physical IOS device. Iphone.
  • Using Expo 40.0.0 with corresponding RN SDK, not ejected.
  • Using expo-image-picker to get image.
  • Using NGROK to get requests through to my localhost server from my phone.
  • All other requests to my server from React Native work fine, it's only when I try to uplaod a file
  • Image renders fine from supplied URI, so it's getting the right source.
  • Form Data source from above:

{ "name": "CAPS-FILE-NAME.jpg", "type": "image/jpeg", "uri": "file:///var/mobile/Containers/Data/Application/CAPS-PATHING/Library/Caches/ExponentExperienceData/project-src-pathing/ImagePicker/CAPS-FILE-NAME.jpg", }

Things tried:

  • Using Content-Type header: "multipart/form-data"
  • Using /private instead of file://
  • Using Postman to hit my server through NGROK, which works
  • Changing my Expo/RN to 38.0.0
  • Getting base64 -> blob -> formData, same result
  • Many other things I've forgotten now. If it's on Google results, I've tried it.

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

For anyone who gets stuck with this also, I switched to using XMLHttpRequest instead of fetch and it miraculously works now. Not sure why fetch is broken in RN, but at least there's a solution.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...