SHUBHAM SONAR
SHUBHAM SONAR

Reputation: 1

RNFS File Disappears Before Upload on iOS After Encryption (Works on Android)

I am working on a React Native application that:

Picks a file using react-native-document-picker. Moves the file to persistent storage using react-native-fs (RNFS). Encrypts the file using AES-256. Uploads the encrypted file to a backend. This setup works perfectly on Android, but on iOS (both simulator and real devices), the file "disappears" before uploading. Here’s what I observe:

File is picked successfully. ✅ File is moved to persistent storage (RNFS.DocumentDirectoryPath). ✅ File is encrypted successfully and stored with _encrypted suffix. ✅ Upload request is triggered. ✅ Suddenly, the encrypted file does not exist. ❌ "No such file" error.

logs from ios simulator LOG 🚀 Moving file to persistent directory: /Users/.../Documents/Pdf LOG ✅ File successfully moved: file:///Users/.../Documents/Pdf LOG 🔐 Reading file... LOG 🔐 Encrypting file... LOG ✅ File encrypted successfully! LOG ✅ Encrypted file confirmed at: file:///Users/.../Documents/Pdf_encrypted LOG 📤 Payload for /files/upload: {"fileKey": "Pdf", "filename": "Pdf.pdf"} LOG POST request to: https://mybackend.com/files/upload LOG ERROR No such file 'file:///Users/.../Documents/Pdf_encrypted'

const moveFileToPersistentDirectory = async (sourceUri, newFileName) => {
  try {
    const destinationPath = `${RNFS.DocumentDirectoryPath}/${newFileName}`;
    console.log(`🚀 Moving file from: ${sourceUri} to: ${destinationPath}`);

    await RNFS.moveFile(sourceUri.replace("file://", ""), destinationPath);
    
    if (!(await ensureFileExists(destinationPath))) {
      throw new Error("File move failed or file inaccessible.");
    }

    console.log(`✅ File successfully moved to: ${destinationPath}`);
    return `file://${destinationPath}`;
  } catch (error) {
    console.error("❌ Error moving file:", error.message);
    throw new Error("Failed to move file.");
  }
};

const encryptAndSaveFile = async (filePath, encryptionKey) => {
  try {
    console.log("🔐 Reading file...");
    const fileContent = await RNFS.readFile(filePath.replace("file://", ""), "base64");

    console.log("🔐 Encrypting file...");
    const encryptedData = await encryptAES256(fileContent, encryptionKey);
    console.log("✅ File encrypted successfully!");

    const encryptedFilePath = `${filePath}_encrypted`;
    await RNFS.writeFile(encryptedFilePath, `${encryptedData.cipher}__${encryptedData.iv}`, "utf8");

    if (!(await ensureFileExists(encryptedFilePath))) {
      throw new Error("Encrypted file disappeared before upload.");
    }

    console.log(`✅ Encrypted file saved at: ${encryptedFilePath}`);
    return `file://${encryptedFilePath}`;
  } catch (error) {
    console.error("❌ Error encrypting file:", error.message);
    throw new Error("Failed to encrypt file.");
  }
};

Upvotes: 0

Views: 6

Answers (0)

Related Questions