预览远程 URL(PDF、doc、img)文件 [英] Preview a remote URL (PDF, doc, img) file
问题描述
我在 react-native 应用程序中预览远程 URL 时遇到问题.可以是PDF、DOC、IMG等,有的建议是用react-native-fs下载,然后看看如何预览.抱歉无法想出任何代码,因为我是 react-native 的新手.有像文档选择器这样的库,我可以在其中从移动设备中选择文件并进行预览.但我正在寻找一个专门用于远程 URL 的通用查看器,它可以显示常见格式,如 PDF、doc、docx、img 等.我找不到这样的东西.
I am facing issue while previewing remote URL inside my react-native application. It can be PDF, DOC, IMG etc. Some suggestions are to use react-native-fs to download and then see how to preview it. Sorry could not come up with any code as I am new to react-native. There are libraries like documentpicker where I can pick the file from mobile and preview it. But I am looking for a generic viewer specially for remote URL which can display the common formats like PDF, doc, docx, img etc. I could not find anything like such.
推荐答案
我们可以使用这两个库来预览这样的 URL 文件.
We can preview URL files like this using these two libraries.
- react-native-file-viewer
- react-native-fs
这是完整的代码.
import React, { Component } from "react";
import { View, Text, TouchableOpacity } from "react-native";
import FileViewer from "react-native-file-viewer";
import RNFS from "react-native-fs";
export default class FileViewerSample extends Component {
onPress = async () => {
// These all formats are acceptable.
// 'www.adobe.com/content/dam/Adobe/en/devnet/pdf/pdfs/PDF32000_2008.pdf';
// 'https://file-examples-com.github.io/uploads/2017/02/file-sample_100kB.doc';
// 'https://www.w3.org/WAI/ER/tests/xhtml/testfiles/resources/pdf/dummy.pdf';
// 'https://scholar.harvard.edu/files/torman_personal/files/samplepptx.pptx';
// 'https://file-examples-com.github.io/uploads/2017/02/file_example_XLS_10.xls';
// Put your url here -----
const url =
"https://file-examples-com.github.io/uploads/2017/02/file-sample_100kB.doc";
// -----
// this will split the whole url.
const f2 = url.split("/");
// then get the file name with extention.
const fileName = f2[f2.length - 1];
// const fileExtention = url.split(".")[3];
// create a local file path from url
const localFile = `${RNFS.DocumentDirectoryPath}/${fileName}`;
const options = {
fromUrl: url,
toFile: localFile,
};
// last step it will download open it with fileviewer.
RNFS.downloadFile(options)
.promise.then(() => FileViewer.open(localFile))
.then(() => {
// success
// Here you can perform any of your completion tasks
})
.catch((error) => {
// error
});
};
render() {
return (
<View
style={{
alignItems: "center",
justifyContent: "center",
// backgroundColor: 'red',
flex: 1,
}}>
<TouchableOpacity
onPress={this.onPress}
style={{ backgroundColor: "gray", padding: 20 }}>
<Text style={{ fontSize: 25 }}> App </Text>
</TouchableOpacity>
</View>
);
}
}
希望能帮到你.您可以根据自己的喜好进行更多修改.
Hope this will help you out. you can modify it more according to your preference.
这篇关于预览远程 URL(PDF、doc、img)文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!