如何在 React Native Expo 中将图像保存到媒体库

How do I save an image to Media Library in React Native Expo

我试图让用户长按下载图片,在 Expo 文档中搜索后我已经找到了一些方法,但我不确定为什么它不起作用!

这是我的代码:

import React from 'react'
import { Image } from 'react-native-elements'
import { ActivityIndicator, StyleSheet, View, TouchableOpacity } from 'react-native'
import * as MediaLibrary from 'expo-media-library';
import * as Permissions from 'expo-permissions';

const Img = () => {

  const download = async (uri) => {
    const { status } = await Permissions.askAsync(Permissions.MEDIA_LIBRARY);

    if (status === 'granted') {
      let uriString = uri.toString();
      const asset = MediaLibrary.createAssetAsync(uriString);
      await MediaLibrary.createAlbumAsync("DownLoads", asset);
    }
  }

  return (
    <View style={{ flex: 1, alignItems: "center", justifyContent: "center" }}>
      <TouchableOpacity activeOpacity={0.2}>
        <Image source={{ uri: "https://miro.medium.com/max/1838/1*mk1-6aYaf_Bes1E3Imhc0A.jpeg" }}
        style={{ width: 300, height: 300 }}
        onLongPress={download(Image.uri)}
        PlaceholderContent={<ActivityIndicator />} />
      </TouchableOpacity>
    </View>
  )
}

export default Img

const styles = StyleSheet.create({})

我是不是漏了什么?

这是旧的但是... createAssetAsync 是一种在本地文件上调用的方法。这是一种组织媒体的方式。

const asset = MediaLibrary.createAssetAsync(uriString);

MediaLibrary.createAssetAsync(localUri) - localUri (string) - 图像或视频文件的 URI。它必须包含扩展名。在 Android 上它必须是本地路径,因此它必须以 file:///.

开头

您必须先使用 FileSystem.downloadAsync to FileSystem.documentDirectory 下载它。

const localuri = await FileSystem.downloadAsync(uri, FileSystem.documentDirectory + filename)
const asset = await MediaLibrary.createAssetAsync(localuri)
const album = await MediaLibrary.createAlbumAsync("DownLoads", asset);