javascript - 无法从 expo react native 中的 url 下载图像到本地目录

标签 javascript react-native expo filesystems

在构建我的应用程序文件后,我无法在 expo 应用程序(Android 的 React Native)中下载图像,但我可以在使用 expo 客户端调试应用程序时下载图像

      import * as Sharing from 'expo-sharing';
      import * as FileSystem from 'expo-file-system';
      import * as MediaLibrary from 'expo-media-library';
      import * as Permissions from "expo-permissions";
    
       const downloadFtn = async () => {
            console.log("downloadFtn");
            const fileUri: string = `${FileSystem.documentDirectory}test.png`;
            const downloadedFile: FileSystem.FileSystemDownloadResult = await FileSystem.downloadAsync("https://i.ibb.co/K5Tyv2C/img-5-1.png", fileUri);
            console.log(FileSystem.documentDirectory);
            console.log(downloadedFile.status);
            if (downloadedFile.status != 200) {
                console.log(downloadedFile);
            } else {
                const perm = await Permissions.askAsync(Permissions.MEDIA_LIBRARY);
                if (perm.status != 'granted') {
                    return;
                }

                try {
                    const asset = await MediaLibrary.createAssetAsync(downloadedFile.uri);
                    const album = await MediaLibrary.getAlbumAsync('Download');
                    if (album == null) {
                        await MediaLibrary.createAlbumAsync('Download', asset, false);
                    } else {
                        await MediaLibrary.addAssetsToAlbumAsync([asset], album, false);
                    }
                } catch (e) {
                    handleError(e);
                }
            }
        }

最佳答案

这是我的代码,运行良好

import {shareAsync} from "expo-sharing";
import * as MediaLibrary from 'expo-media-library';
import * as FileSystem from 'expo-file-system';
function getAllUrlParams(url) {

  // get query string from url (optional) or window
  var queryString = url ? url.split('?')[1] : window.location.search.slice(1);

  // we'll store the parameters here
  var obj = {};

  // if query string exists
  if (queryString) {

    // stuff after # is not part of query string, so get rid of it
    queryString = queryString.split('#')[0];

    // split our query string into its component parts
    var arr = queryString.split('&');

    for (var i = 0; i < arr.length; i++) {
      // separate the keys and the values
      var a = arr[i].split('=');

      // set parameter name and value (use 'true' if empty)
      var paramName = a[0];
      var paramValue = typeof (a[1]) === 'undefined' ? true : a[1];

      // (optional) keep case consistent
      paramName = paramName.toLowerCase();
      if (typeof paramValue === 'string') paramValue = paramValue.toLowerCase();

      // if the paramName ends with square brackets, e.g. colors[] or colors[2]
      if (paramName.match(/\[(\d+)?\]$/)) {

        // create key if it doesn't exist
        var key = paramName.replace(/\[(\d+)?\]/, '');
        if (!obj[key]) obj[key] = [];

        // if it's an indexed array e.g. colors[2]
        if (paramName.match(/\[\d+\]$/)) {
          // get the index value and add the entry at the appropriate position
          var index = /\[(\d+)\]/.exec(paramName)[1];
          obj[key][index] = paramValue;
        } else {
          // otherwise add the value to the end of the array
          obj[key].push(paramValue);
        }
      } else {
        // we're dealing with a string
        if (!obj[paramName]) {
          // if it doesn't exist, create property
          obj[paramName] = paramValue;
        } else if (obj[paramName] && typeof obj[paramName] === 'string'){
          // if property does exist and it's a string, convert it to an array
          obj[paramName] = [obj[paramName]];
          obj[paramName].push(paramValue);
        } else {
          // otherwise add the property
          obj[paramName].push(paramValue);
        }
      }
    }
  }

  return obj;
}
export class fileAPI {
    downloadFile = async (url) => {
        let params = getAllUrlParams(url);
        console.log("params", params);
        let file_name = params.name;
        console.log("file_name", file_name)
        if (file_name !== null) {
            FileSystem.downloadAsync(
                url,
                FileSystem.documentDirectory + file_name
            )
                .then(async ({uri}) => {
                    console.log('Finished downloading to ', uri);
                    MediaLibrary.createAssetAsync(uri).then(asset => {
                        console.log('asset', asset);
                        this.share(asset)
                        MediaLibrary.createAlbumAsync('albumnameyouneedtosave', asset)
                            .then(() => {
                                console.log("download complete");
                            })
                            .catch(error => {
                                console.log("issue with download contact support");
                            });
                    });

                })
                .catch(error => {
                    console.error(error);
                });
        }
    };
    share = async (asset) => {
        console.log(asset.filename.split("."))
        console.log(asset.filename.split(".").length)
        await shareAsync(asset.uri, {
            UTI: "." + asset.filename.split(".")[asset.filename.split(".").length - 1],
            mimeType: "application/" + asset.filename.split(".")[asset.filename.split(".").length - 1]
        });
    }
}

关于javascript - 无法从 expo react native 中的 url 下载图像到本地目录,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/68512225/

相关文章:

javascript - 有哪些好的纯 JavaScript 教程和引用资料?

javascript - 这是检查 isarray 的最佳方法

javascript - 从数据 uri 将图像上传到服务器

reactjs - 如何修复流量错误 "TouchHistoryMath. Duplicate module provider"

javascript dojo 工具包在应用程序中使用全局对象

android - 崩溃后的 react native 应用程序显示闪屏

react-native - 如何在 React Native 中设置默认字体系列?

ios - Expo 应用因 WebView 和用户字体的无效二进制文件而被拒绝

javascript - FlatList 仅在至少有 2 个项目时可见

javascript - 为什么 'formData' 在 React Native Android 模拟器的 'axios 0.26.1' 中不起作用?