【问题标题】:Error: Could not get the file's extension |How do save an image to Media Library in React Native Expo错误:无法获取文件的扩展名|如何在 React Native Expo 中将图像保存到媒体库
【发布时间】:2022-07-20 06:16:19
【问题描述】:
import * as FileSystem from 'expo-file-system';
import * as MediaLibrary from 'expo-media-library';
const handleDownloadImage = async () => {
await MediaLibrary.requestPermissionsAsync();
const localuri = await FileSystem.downloadAsync(
'https://64.media.tumblr.com/a92e72902106507c59ff8d0ca26abfc0/1d7f633f39b0a908-34/s1280x1920/a7073bbdeb1033b989e040fd216266be8ba31341.jpg',
FileSystem.documentDirectory + 'demo.jpg'
);
const asset = await MediaLibrary.createAssetAsync(localuri.toString());
const album = await MediaLibrary.createAlbumAsync('DownLoads', asset);
console.log(album);
};
我无法将图像保存到下载文件夹,
我使用没有 2 个文件夹 android 和 ios 的 expo
【问题讨论】:
标签:
javascript
android
reactjs
react-native
expo
【解决方案1】:
此代码将实现您的需求,希望对您有所帮助
//use these imports
import * as FileSystem from 'expo-file-system';
import * as Sharing from 'expo-sharing';
import * as Permissions from 'expo-permissions';
import * as MediaLibrary from 'expo-media-library';
const Download = async (url: string, name: string) => {
setLoading(true);
let remoteUrl = `${BASE_URL_NO_API}${url}`;
let localPath = FileSystem.documentDirectory + name;
let downloadedFile = await FileSystem.downloadAsync(remoteUrl, localPath);
if (downloadedFile.status != 200) {
Alert.alert('error', 'error in downloading file');
// handleError();
setLoading(false);
}
//handle ios non image files first
const imageFileExts = ['jpg', 'png', 'gif', 'heic', 'webp', 'bmp', 'jpeg'];
if (
Platform.OS == 'ios' &&
imageFileExts.every(x => !downloadedFile.uri.endsWith(x))
) {
const UTI = 'public.item';
const shareResult = await Sharing.shareAsync(downloadedFile.uri, { UTI });
Alert.alert('Success', 'File Saved');
setLoading(false);
}
const perm = await Permissions.askAsync(Permissions.MEDIA_LIBRARY);
if (perm.status != 'granted') {
setLoading(false);
return;
}
try {
const asset = await MediaLibrary.createAssetAsync(downloadedFile.uri);
const album = await MediaLibrary.getAlbumAsync('Download');
if (album == null) {
await MediaLibrary.createAlbumAsync('Download', asset, false);
if (imageFileExts.every(x => !downloadedFile.uri.endsWith(x))) {
Alert.alert('Success', 'File Saved To Download Folder');
setLoading(false);
} else {
Alert.alert('Success', 'Image Saved To Gallery');
setLoading(false);
}
} else {
await MediaLibrary.addAssetsToAlbumAsync([asset], album, false);
if (imageFileExts.every(x => !downloadedFile.uri.endsWith(x))) {
Alert.alert('Success', 'File Saved To Download Folder');
setLoading(false);
} else {
Alert.alert('Success', 'Image Saved To Gallery');
setLoading(false);
}
}
} catch (e) {
Alert.alert('error', 'error in saving file');
setLoading(false);
// handleError(e);
}
};