推荐开源项目:React Native Qiniu SDK - 高效可靠的七牛云存储客户端SDK
// 安装七牛云SDK
npm install qiniu-js
// 在React Native项目中使用七牛云SDK上传文件
import React, { useState } from 'react';
import { Button, Text, View } from 'react-native';
import * as FileSystem from 'expo-file-system';
import * as MediaLibrary from 'expo-media-library';
import uuidv4 from 'uuid/v4';
import * as Permissions from 'expo-permissions';
import * as ImagePicker from 'expo-image-picker';
import * as Constants from 'expo-constants';
import * as mime from 'mime-types';
import * as SDK from 'qiniu-js';
export default function App() {
const [uploadResult, setUploadResult] = useState(null);
const uploadToQiniu = async (fileUri) => {
const { status } = await Permissions.askAsync(Permissions.CAMERA_ROLL);
if (status !== 'granted') {
alert('无权访问相册');
return;
}
const credentials = await Secrets.getQiniuCredentials();
const putPolicy = new SDK.rs.PutPolicy({ scope: credentials.bucket });
const uploadToken = putPolicy.uploadToken(credentials.mac);
const key = `${uuidv4()}.${mime.extension(fileUri)}`;
const observer = {
next(res) {
// 主要用于设置上传进度
console.log(res.total.percent);
},
error(err) {
console.error(err);
setUploadResult(err);
},
complete(res) {
console.log(res);
setUploadResult(res);
},
};
SDK.upload(fileUri, { key, token: uploadToken }, observer);
};
// 选择图片并上传
const pickImageAndUpload = async () => {
let pickerResult = await ImagePicker.launchImageLibraryAsync({
mediaTypes: ImagePicker.MediaTypeOptions.Images,
allowsEditing: true,
aspect: [4, 3],
});
if (!pickerResult.cancelled) {
uploadToQiniu(pickerResult.uri);
}
};
return (
<View>
<Button title="选择图片" onPress={pickImageAndUpload} />
{uploadResult && <Text>{JSON.stringify(uploadResult)}</Text>}
</View>
);
}
这段代码示例展示了如何在React Native应用中使用七牛云的JavaScript SDK进行文件上传。首先,它请求相册权限,然后使用uuid生成唯一的文件名,并获取上传凭证。最后,它调用七牛云的SDK.upload函数来上传文件。这个例子简洁明了,并包含了错误处理和进度跟踪,对开发者有很好的教育意义。
评论已关闭