在 React native 中访问缓存图像以上传到 S3

Accessing Cache Images to upload to S3, in React native

使用react-native-vision-camera,看到图片有路径。它似乎可以通过 react native 标签读取。

我尝试使用此路径上传(我对 android 使用了 file://,对 IOS 也使用了 file://),但失败了。每次文件被检测为“jpeg”或“jpg”但我无法访问它。

下载(从我上传的S3亚马逊)并将jpg转换为txt后,我只找到“file://path”。

import { Storage } from "aws-amplify";
    export default async function s3UploadBackup(file, user) {
        let formatted_date = moment().format("DD-MM-YYYY");
        let filePath = file.split("/");
        let fileImageName = filePath[filePath.length - 1];
        try {
            console.log("Files contains :" + JSON.stringify(file));
    
            // example of one of the URL I used  "file:///storage/emulated/0/Android/data/com.app/files/Pictures/image-c64a66b3-489d-4af6-bf93-7adb507ceda1790666367.jpg"
            const fileName = `${formatted_date}---${user.businessName}---${user.phoneNumber}---${user.location}---${fileImageName}`;
            return Storage.put(uploadBackup.path + user.sub + "/" + user.phoneNumber + "/" + fileName, file, {
                // contentType: "image/jpeg"
                contentType: file.mime
            })
        } catch(error) {
            console.log(error);
        } 
    }

A​​WS-AMPLIFY 支持以 BLOB 格式上传文件并转换为指定的文件扩展名(JPEG、PNG、...)。

假设我们有本地文件 URI - file:///storage/emulated/0/Android/data/com.app/files/Pictures/image-c64a66b3-489d-4af6-bf93-7adb507ceda1790666367.jpg

让我们重构s3UploadBackup函数

import { Storage } from "aws-amplify";
    export default async function s3UploadBackup(file, user) {
        let formatted_date = moment().format("DD-MM-YYYY");
        let filePath = file.split("/");
        let fileImageName = filePath[filePath.length - 1];
        try {
            console.log("Files contains :" + JSON.stringify(file));
    
            // example of one of the URL I used  "file:///storage/emulated/0/Android/data/com.app/files/Pictures/image-c64a66b3-489d-4af6-bf93-7adb507ceda1790666367.jpg"
            const fileName = `${formatted_date}---${user.businessName}---${user.phoneNumber}---${user.location}---${fileImageName}`;

  const blob = await new Promise((resolve, reject) => {
    const xhr = new XMLHttpRequest();
    xhr.onload = function () {
      resolve(xhr.response);
    };
    xhr.onerror = function (e) {
      reject(new TypeError("Network request failed"));
    };
    xhr.responseType = "blob";
    xhr.open("GET", localPath, true);
    xhr.send(null);
  });


  await Storage.put("yourKeyHere", blob, {
       contentType: "image/jpeg", // contentType is optional
    });
// We're done with the blob, close and release it
  blob.close();
        } catch(error) {
            console.log(error);
// We're done with the blob, close and release it
  blob.close();
        } 
    }