探索 React Native Uploader:实现高效文件上传的利器
import React, { useState } from 'react';
import { StyleSheet, Text, View, Button, Alert } from 'react-native';
import RNFetchBlob from 'rn-fetch-blob';
const App = () => {
const [uploading, setUploading] = useState(false);
const uploadFile = () => {
const path = 'path/to/your/file';
const uploadUrl = 'https://your.api/upload';
setUploading(true);
const options = {
fileUpload: true,
fileKey: 'file', // 后端接收文件的字段名
fileName: 'image.jpg', // 文件名,可以自定义
mimeType: 'image/jpeg', // 文件类型
// 其他可能需要的参数,如headers等
};
RNFetchBlob.fetch('POST', uploadUrl, options)
.uploadProgress((written, total) => {
console.log(`Uploaded ${written}/${total}`);
})
.then(resp => {
console.log('uploaded', resp.path());
Alert.alert('File Uploaded', 'File has been uploaded successfully', [{text: 'OK', onPress: () => console.log('OK Pressed')}]);
})
.catch(err => {
console.log('err', err);
Alert.alert('Upload Error', 'There was an error uploading the file', [{text: 'OK', onPress: () => console.log('OK Pressed')}]);
})
.finally(() => {
setUploading(false);
});
};
return (
<View style={styles.container}>
<Button
onPress={uploadFile}
title="Upload File"
disabled={uploading}
/>
</View>
);
}
const styles = StyleSheet.create({
container: {
flex: 1,
justifyContent: 'center',
alignItems: 'center',
},
});
export default App;
这段代码展示了如何使用rn-fetch-blob
库在React Native应用中实现文件的上传功能。它定义了一个简单的App组件,其中包含了一个按钮,用户可以点击它来触发文件上传的动作。上传过程中,使用了一个状态变量uploading
来控制按钮的禁用状态,并通过Alert
组件在上传成功或失败时给用户反馈。这是一个实用且简洁的文件上传示例,适合作为学习和实践文件上传功能的起点。
评论已关闭