我想知道如何在React Native中为从数据库检索图像并将其显示给用户的应用程序建模。我打算将图像存储在目录中,并让数据库存储所有图像的文件路径。
但是,我发现其他人遇到的一个问题是React Native需要源代码中的完全静态文件路径。我经常看到的一种解决方案是使用单个索引或switch语句引用所有图像。我认为该模型不适用于我的应用程序,因为用户应该能够上传自己的图像,然后将其存储在服务器上,并将其文件路径放入数据库中,但不会在交换机中表示出来声明。对于这种情况可能会有什么样的解决方案?
答案 0 :(得分:1)
对于我的react-native应用程序,为了上传照片,我使用react-native-image-picker从用户的设备中选择图片,并使用rns3将图片发送到AWS s3。对于图片的文件名,我使用了应用程序名称以及js库来动态创建唯一的文件名。您也可以使用uuid。
例如:
ImagePicker.showImagePicker(options, response => {
if (response.didCancel) {
// alert cancel
} else if (response.error) {
// alert error
} else {
const { uri } = response;
const extensionIndex = uri.lastIndexOf(".");
const extension = uri.slice(extensionIndex + 1);
const file = {
uri,
name: `${YourAppName}_${moment.utc().format("YYYY-MM-DD-HH-mm-ss")}.${extension}`,
type: "image/jpeg"
};
const options = {
keyPrefix: ****,
bucket: ****,
region: ****,
accessKey: ****,
secretKey: ****
};
// send file to aws s3 and to your db ...
RNS3.put(file, options)
.progress(event => {
console.log(`percent: ${event.percent}`);
})
.then(response => {
if (response.status !== 201) {
console.error(response.body);
return;
}
// this will contain the image url
let image = response.headers.Location;
// send image url to your db
})
})
要显示图像,只需使用存储在数据库中的URL。