Niy*_*ooo 7 javascript reactjs react-native expo aws-amplify
我正在尝试将图像转换为 blob,以便将其上传到 aws s3 存储。在使用 expo-image-picker 选择图像后,我需要将图像转换为 blob,然后使用 fetch 转换为 blob,但它会导致以下错误。
错误 RangeError:无法构造“响应”:提供的状态 (0) 超出范围 [200, 599]。,js 引擎:hermes
这是我目前的情况:
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',
},
});
Run Code Online (Sandbox Code Playgroud)
获取语句导致错误。
let response = await fetch(result.assets[0].uri);
我尝试在博览会小吃中构建它,并且运行良好。我没有收到任何错误。但它在我的本地设置上崩溃了。
当我将 Android 的 targetSDK 版本更新到 33 以符合新的 Google Play 规则时,我开始遇到这个问题。
按照此处提供的答案解决了我的问题。这是答案中提到的 util 函数,但有一些解释性注释:
/**
* 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);
});
};
Run Code Online (Sandbox Code Playgroud)
该函数的工作原理是使用 XMLHttpRequest API 向文件 URI 发送 HTTP GET 请求,请求文件数据。XMLHttpRequest.responseType 属性设置为“blob”,因此 XMLHttpRequest 的响应是表示文件数据的 Blob。
XMLHttpRequest 是一个较低级别的 API,可以对请求和响应进行更精细的控制。
正如链接答案中提到的,fetch 没有一个好的方法来处理本地文件 URL(通常在 React Native 中使用),但 XMLHttpRequest 可以更优雅地处理这些。
归档时间: |
|
查看次数: |
3082 次 |
最近记录: |