我目前正尝试使用提取将一批相当大的照片(约150-200张)作为Base64一次上传到Cloudinary API。这是Expo(SDK 35)不支持Blob和Firebase不接受Base64图像后的痛苦解决方法。
在我的应用程序中,照片存储在子目录中。我希望得到的结果是具有一个包含目录列表并分别在每个目录中上载每个图像的函数。当前,当我运行此函数时,它会适当地在目录中查找并返回目录中所有文件的数组。但是,它不尝试调用上载图像并等待完成然后再尝试下一次上载,而是尝试一次上载每张照片。
理想情况下,该功能会在移至下一个目录之前,将子目录中的所有照片一张一张地上传。我的代码在下面列出。
const hardDirs = [
{
photoDirectory: "exampleDir1",},{
photoDirectory: "exampleDir2",{
photoDirectory: "exampleDir3",{
photoDirectory: "exampleDir4",];
//Parse through directories
async function _directoryNavigator(documentId) {
//TODO: SWITCH TO ASYNCSTORAGE KEY FOR DIRECTORIES
for (let i = 0; i < hardDirs.length; i++) {
let localDir = FileSystem.documentDirectory + hardDirs[i].photoDirectory;
//supply both appropriate path format and name of directory to retrieve files and supply new folder name
let directoryFolder = hardDirs[i].photoDirectory;
//documentId is auto-generated string supplied by Firebase Cloud Firestore for associated scope JSON schema
let firebaseDoc = documentId;
console.log("getting directory " + directoryToUpload);
await _uploadFromDirectory(localDir,directoryFolder,firebaseDoc);
}
}
//Return list of each file in directory,create upload
_uploadFromDirectory = async (localDir,firebaseDoc) => {
console.log("enumerate from directory");
let directoryContents = await FileSystem.readDirectoryAsync(localDir);
for (let i = 0; i < directoryContents.length; i++) {
let uri = directoryContents[i];
console.log("getting image inside directory" + imageFile);
await createFileUpload(imageFile,localDir,firebaseDoc);
}
}
createFileUpload = async (uri,firebaseDoc) => {
console.log("create base64 file for upload");
let imagePath = `${localDir}/${uri}`;
//console.log("uploadAsFile",imagePath);
const response = await FileSystem.readAsStringAsync(
imagePath,{
encoding: FileSystem.EncodingType.Base64,});
let base64Img = `data:image/jpg;base64,${response}`;
let apiUrl = 'https://api.cloudinary.com/v1_1/username/image/upload';
let data = {
"file": base64Img,"upload_preset": "PRESET","folder": `${directoryFolder}`,"public_id": `${firebaseDoc}/${directoryFolder}/${uuid.v4()}`
};
const upload = await uploadImage(apiUrl,data);
}
async function uploadImage(apiUrl,data) {
try {
console.log("upload image")
let response = await fetch(apiUrl,{
body: JSON.stringify(data),headers: {
'content-type': 'application/json'
},method: 'POST',});
let data = await response.json();
return data.secure_url;
console.log(data.secure_url);
} catch(err) {
console.error(err);
}
}
对于React Native来说,我还是一个相对较新的人,并试图尽可能地更好地理解ES6。任何指导将不胜感激。提前致谢。