最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - React Native Blob fetch throws error: Failed to construct 'Response': The status provided (0) is ou

programmeradmin4浏览0评论

I am trying to convert an image to blob for uploading it to aws s3 storage.I need to connvert image to blob after selecting the image with expo-image-picker the convert to blob using fetch but it is causing the following error.

ERROR RangeError: Failed to construct 'Response': The status provided (0) is outside the range [200, 599]., js engine: hermes

This is my current situation :

import { Button, StyleSheet, Text, View } from 'react-native';
import * as ImagePicker from 'expo-image-picker'
export default function App() {
  const PickImage = async()=>{
    let result = await ImagePicker.launchImageLibraryAsync({
      quality:1,
      mediaTypes:ImagePicker.MediaTypeOptions.Images,
    })
    if(!result.canceled){
      let response = await fetch(result.assets[0].uri);
      let blob = await response.blob();
      
      //code to upload image
    }
  }
  return (
    <View style={styles.container}>
      <Button onPress={PickImage} title='TEST'/>
    </View>
  );
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor: '#fff',
    alignItems: 'center',
    justifyContent: 'center',
  },
});

the fetch ststement is causing error. let response = await fetch(result.assets[0].uri);

I tried to build it in expo snack and it is working fine. I am not getting any errors.but it is crashing on my local setup.

I am trying to convert an image to blob for uploading it to aws s3 storage.I need to connvert image to blob after selecting the image with expo-image-picker the convert to blob using fetch but it is causing the following error.

ERROR RangeError: Failed to construct 'Response': The status provided (0) is outside the range [200, 599]., js engine: hermes

This is my current situation :

import { Button, StyleSheet, Text, View } from 'react-native';
import * as ImagePicker from 'expo-image-picker'
export default function App() {
  const PickImage = async()=>{
    let result = await ImagePicker.launchImageLibraryAsync({
      quality:1,
      mediaTypes:ImagePicker.MediaTypeOptions.Images,
    })
    if(!result.canceled){
      let response = await fetch(result.assets[0].uri);
      let blob = await response.blob();
      
      //code to upload image
    }
  }
  return (
    <View style={styles.container}>
      <Button onPress={PickImage} title='TEST'/>
    </View>
  );
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor: '#fff',
    alignItems: 'center',
    justifyContent: 'center',
  },
});

the fetch ststement is causing error. let response = await fetch(result.assets[0].uri);

I tried to build it in expo snack and it is working fine. I am not getting any errors.but it is crashing on my local setup.

Share Improve this question edited Jul 29, 2023 at 17:57 FutureJJ 2,6881 gold badge24 silver badges34 bronze badges asked Jul 24, 2023 at 12:51 NiyasinNiyasin 1331 silver badge7 bronze badges 3
  • 1 Probably this error is related to Hermes, maybe you can legacy engine. Or try to wrap let response = await fetch(result.assets[0].uri); with try/catch block. – Michael Bahl Commented Jul 24, 2023 at 13:27
  • i tried it.but it is not working. still getting error – Niyasin Commented Jul 24, 2023 at 13:37
  • Here is a github issue tracking this: github./facebook/react-native/issues/38625 – Staeff Commented Aug 22, 2023 at 9:52
Add a ment  | 

2 Answers 2

Reset to default 14

I started facing this issue when I updated my targetSDK version to 33 for Android to ply with new Google Play rules.

Following the answer provided here fixed the issue for me. Here is the util function mentioned in the answer but with some explanatory ments:

/**
 * Function to convert a URI to a Blob object
 * @param {string} uri - The URI of the file
 * @returns {Promise} - Returns a promise that resolves with the Blob object
 */
export function uriToBlob(uri: string): Promise<Blob> {
  return new Promise((resolve, reject) => {
    const xhr = new XMLHttpRequest();

    // If successful -> return with blob
    xhr.onload = function () {
      resolve(xhr.response);
    };

    // reject on error
    xhr.onerror = function () {
      reject(new Error('uriToBlob failed'));
    };

    // Set the response type to 'blob' - this means the server's response 
    // will be accessed as a binary object
    xhr.responseType = 'blob';

    // Initialize the request. The third argument set to 'true' denotes 
    // that the request is asynchronous
    xhr.open('GET', uri, true);

    // Send the request. The 'null' argument means that no body content is given for the request
    xhr.send(null);
  });
};

The function works by using the XMLHttpRequest API to send an HTTP GET request to the file URI, requesting the file data. The XMLHttpRequest.responseType property is set to 'blob', so the XMLHttpRequest's response is a Blob that represents the file data.

XMLHttpRequest, is a lower-level API that can give more granular control over the request and response.

As mentioned in the linked answer fetch does not have a good way of handling local file URLs (often used in React Native) but XMLHttpRequest can handle these more gracefully.

I solved this by downgrading the whatwg-fetch because the new verison RN72 upgrades whatwg-fetch to 3.6.17 and causes this type of error.Need to install the version 3.6.2 by

npm install [email protected] 

or

npm install --force [email protected] 

and for me solved this error.

与本文相关的文章

发布评论

评论列表(0)

  1. 暂无评论