【问题标题】:How to get file from cache file from expo image picker如何从 expo 图像选择器的缓存文件中获取文件
【发布时间】:2021-05-14 22:34:27
【问题描述】:

我使用 Expo Image Picker:https://docs.expo.io/versions/latest/sdk/imagepicker/

从图库或相机中获取图像后,它会返回以下结果:

{
  "cancelled":false,
  "height":1611,
  "width":2148,
  "uri":"file:///data/user/0/host.exp.exponent/cache/cropped1814158652.jpg"
}

但是,我得到的只是 uri,我需要文件,如何从缓存 uri 中获取文件?

我需要使用此文件将该文件上传到服务器

module.exports.uploadFile = function(file) {
    return new Promise((resolve, reject) => {
        myServerApi.upload({
            file,
            fileName: file.name, 
        }, function(err, result) {
            if(err) reject(err);
            resolve(result);
        })
    })
}

【问题讨论】:

    标签: react-native expo


    【解决方案1】:

    根据您发布的文档,ImagePicker.launchImageLibraryAsync(options)options 有一个名为 base64 的布尔值:

    base64 (boolean) -- 是否也包含 Base64 格式的图片数据。

    因此,按照文档示例,您可以执行以下操作:

    let result = await ImagePicker.launchImageLibraryAsync({
      mediaTypes: ImagePicker.MediaTypeOptions.All,
      allowsEditing: true,
      base64: true, //<-- boolean base64
      aspect: [4, 3],
      quality: 1,
    });
    

    result 将是:

    {
       "cancelled":false,
       "height":1611,
       "width":2148,
       "uri":"file:///data/user/0/host.exp.exponent/cache/cropped1814158652.jpg",
       "base64": "......" //<-- base64 image
    }
    

    所以你可以将result 传递给你的函数uploadFile 来存储图像。比如:

    result.name = "myImage";
    uploadFile(result);
    

    然后,正如文档所说,您可以通过这种方式将 base64 图像也用作 uri:

    如果 base64 选项为真,则包含 base64 属性,并且是所选图像的 JPEG 数据的 Base64 编码字符串。如果你在前面加上“data:image/jpeg;base64”来创建一个数据 URI,你可以将它用作 Image 元素的源;例如:.

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-05-14
      • 1970-01-01
      • 2020-04-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-08-19
      • 2015-09-08
      相关资源
      最近更新 更多