【问题标题】:How to open downloaded photo using gallery app in React Native Expo?如何在 React Native Expo 中使用图库应用打开下载的照片?
【发布时间】:2020-01-01 00:30:49
【问题描述】:

我面临一个问题,无法弄清楚如何实施此类操作。我想从外部来源下载照片,然后我想在图库中打开它。

查看此来源:How to open iOS gallery app from React Native app

这里一位开发人员建议使用此代码:

openPhotos = () =>{
switch(Platform.OS){
  case "ios":
    Linking.openURL("photos-redirect://");
  break;
  case "android":
    Linking.openURL("content://media/internal/images/media");
  break;
  default:
    console.log("Could not open gallery app");
 }
}

此代码确实打开了图库,但是当我选择默认图库应用时,它会显示黑屏,如果我选择谷歌照片应用,它会打开没有黑屏的图库。

我的问题是如何重构我的代码,以便能够下载照片并在图库中打开下载的照片?

组件代码:

import React from "react";
import {View,Text, StyleSheet,Platform,Image,Alert} from "react-native";
import PhotoComments from "./PhotoComments";
import moment from "moment";
import * as MediaLibrary from "expo-media-library";
import * as FileSystem from "expo-file-system";
import * as Permissions from "expo-permissions";
import { Button } from "react-native-elements";
import { Linking } from "expo";

function downloadFile(uri) {
  let filename = uri.split("/");
  filename = filename[filename.length - 1];
  let fileUri = FileSystem.documentDirectory + filename;
  FileSystem.downloadAsync(uri, fileUri)
    .then(({ uri }) => {
      saveFile(uri);
    })
    .catch(error => {
      Alert.alert("Error", "Couldn't download photo");
      console.error(error);
    });
}
async function openPhotos(uri) {
  switch (Platform.OS) {
    case "ios":
      Linking.openURL("photos-redirect://");
      break;
    case "android":
      //Linking.openURL("content://media/internal/images/media/");
      Linking.openURL("content://media/internal/images/media");
      break;
    default:
      console.log("Could not open gallery app");
  }
}

async function saveFile(fileUri) {
  const { status } = await Permissions.askAsync(Permissions.CAMERA_ROLL);
  if (status === "granted") {
    const asset = await MediaLibrary.createAssetAsync(fileUri);
    const data = await MediaLibrary.createAlbumAsync("Download", asset, false);
    console.log("deubeuger");
    console.log(data);
    console.log("buger");

    Alert.alert("Success!", JSON.stringify(fileUri));
    openPhotos(fileUri);
  }
}

const PhotoRecord = ({ data }) => {
  return (
    <View style={styles.container}>
      <View style={styles.infoContainer}>
        <Text style={styles.usernameLabel}>@{data.username}</Text>
        <Text style={styles.addedAtLabel}>
          {moment(new Date(data.addedAt)).format("YYYY/MM/DD HH:mm")}
        </Text>
      </View>
      <View style={styles.imageContainer}>
        <Image source={{ uri: data.links.thumb }} style={styles.image} />
      </View>
      <PhotoComments comments={data.photoComments} />
      <View style={styles.btnContainer}>
        <Button
          buttonStyle={{
            backgroundColor: "white",
            borderWidth: 1
          }}
          titleStyle={{ color: "dodgerblue" }}
          containerStyle={{ backgroundColor: "yellow" }}
          title="Add Comment"
        />
        <Button
          onPress={() => downloadFile(data.links.image)}
          style={styles.btn}
          title="Download"
        />
      </View>
    </View>
  );
};

我设法实现了从外部源下载,但找不到有关如何通过图库应用打开下载的照片的有效解决方案。

也许我正在寻找效率不高的解决方案,也许有更好的方法?

【问题讨论】:

    标签: react-native linker expo gallery


    【解决方案1】:

    找不到此问题的理想解决方案。决定开发一个有点不同的应用程序,如果有类似问题的人会搜索这个线程。我制作了下载按钮,它将照片下载到设备

    import React, { useState } from "react";
    import {
      View,
      Text,
      StyleSheet,
      Image,
      Alert,
      TouchableOpacity
    } from "react-native";
    import PhotoComments from "./PhotoComments";
    import moment from "moment";
    import * as MediaLibrary from "expo-media-library";
    import * as FileSystem from "expo-file-system";
    import * as Permissions from "expo-permissions";
    import { Button } from "react-native-elements";
    import ZoomableImage from "./ZoomableImage";
    
    function downloadFile(uri) {
      let filename = uri.split("/");
      filename = filename[filename.length - 1];
      let fileUri = FileSystem.documentDirectory + filename;
      FileSystem.downloadAsync(uri, fileUri)
        .then(({ uri }) => {
          saveFile(uri);
        })
        .catch(error => {
          Alert.alert("Error", "Couldn't download photo");
          console.error(error);
        });
    }
    async function saveFile(fileUri) {
      const { status } = await Permissions.askAsync(Permissions.CAMERA_ROLL);
      if (status === "granted") {
        const asset = await MediaLibrary.createAssetAsync(fileUri);
        await MediaLibrary.createAlbumAsync("Download", asset, false);
        Alert.alert("Success", "Image was successfully downloaded!");
      }
    }
    
    const PhotoRecord = ({ data }) => {
      const [show, setShow] = useState(false);
    
      return (
        <View style={styles.container}>
          <ZoomableImage
            show={show}
            setShow={setShow}
            imageSource={data.links.image}
          />
          <View style={styles.infoContainer}>
            <Text style={styles.usernameLabel}>@{data.username}</Text>
            <Text style={styles.addedAtLabel}>
              {moment(new Date(data.addedAt)).format("YYYY/MM/DD HH:mm")}
            </Text>
          </View>
          <TouchableOpacity
            activeOpacity={1}
            style={styles.imageContainer}
            onLongPress={() => setShow(true)}
          >
            <Image source={{ uri: data.links.thumb }} style={styles.image} />
          </TouchableOpacity>
          <PhotoComments comments={data.photoComments} />
          <View style={styles.btnContainer}>
            <Button
              buttonStyle={{
                backgroundColor: "white",
                borderWidth: 1
              }}
              titleStyle={{ color: "dodgerblue" }}
              containerStyle={{ backgroundColor: "yellow" }}
              title="Add Comment"
            />
            <Button
              onPress={() => downloadFile(data.links.image)}
              style={styles.btn}
              title="Download"
            />
          </View>
        </View>
      );
    };
    
    const styles = StyleSheet.create({
      container: {
        display: "flex",
        flexDirection: "column"
      },
      infoContainer: {
        borderBottomWidth: 1,
        borderColor: "gainsboro",
        display: "flex",
        flexDirection: "row",
        justifyContent: "space-between",
        padding: 15
      },
      usernameLabel: {
        fontSize: 18,
        fontWeight: "bold"
      },
      addedAtLabel: {
        paddingTop: 10,
        color: "#404040"
      },
      imageContainer: {
        width: "100%",
        height: 380
      },
      image: {
        width: "100%",
        height: "100%",
        resizeMode: "cover"
      },
      btnContainer: {
        flex: 1,
        flexDirection: "row",
        marginBottom: 100,
        justifyContent: "space-between"
      }
    });
    
    export default PhotoRecord;
    
    
    • 在我的设备上看起来像这样

    • 如果点击下载按钮,它会将照片下载到设备中

    • 如果用户想要查看图片,他可以长按照片,然后照片会在网页视图模式中打开

    这远非完美,但我可以自己弄清楚。 modal 的代码在这里:

    import React from "react";
    import { Modal, Dimensions, StyleSheet, View } from "react-native";
    import { WebView } from "react-native-webview";
    
    
    const ZoomableImage = ({ show, setShow, imageSource }) => {
      return (
        <Modal
          animationType={"fade"}
          transparent={false}
          visible={show}
          onRequestClose={() => {
            setShow(!show);
          }}
        >
          <View style={styles.container}>
            <WebView source={{ uri: imageSource }} style={styles.image} />
          </View>
        </Modal>
      );
    };
    
    const styles = StyleSheet.create({
      container: {
        flex: 1,
        alignItems: "center",
        justifyContent: "space-between"
      },
      image: {
        height: Math.round(Dimensions.get("window").height),
        width: Math.round(Dimensions.get("window").width),
        flex: 1
      }
    });
    export default ZoomableImage;
    

    无法实现我想要的,但想出了一个稍微不同的解决方案,希望这会对某人有所帮助。

    【讨论】:

    • 寻找相同的东西。需要打开本机画廊,但 WebView 不会为我这样做
    • 试过你的功能,但在IOS上出现这个错误:[未处理的承诺拒绝:错误:资产无法保存到照片库]你面对了吗?
    • 嗯,它不能正常工作,我会在找到解决方案后立即发布答案
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-02-22
    • 2020-12-06
    • 1970-01-01
    • 2022-11-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多