【问题标题】:Trying to download pdf from react native webview尝试从反应原生 webview 下载 pdf
【发布时间】:2020-09-10 17:53:06
【问题描述】:

我知道我似乎无法让它工作。 “onFileDownload={ ( { nativeEvent: { downloadUrl } } ) => {” 已添加,我需要自己的代码来完成这项工作。我尝试使用 expo 文件系统和 expo 共享来下载它,但它不起作用。我想要的是,当他们下载 pdf 而不是预览时,他们可以共享文档或保存它。任何帮助将不胜感激。

下面是我试图让它工作但失败的代码(警报功能工作但没有任何反应):


import React, { Component } from 'react';
import { StyleSheet, ActivityIndicator, View, Platform, PermissionsAndroid, Alert } from 'react-native';
import * as Permissions from 'expo-permissions';
import { WebView } from 'react-native-webview';
//sharing and download
import * as Sharing from 'expo-sharing';
import * as FileSystem from 'expo-file-system';
import { Image, Text, TouchableOpacity, } from 'react-native';
import * as ImagePicker from 'expo-image-picker';

export default function App() {
let [selectedImage, setSelectedImage] = React.useState(null);

let openImagePickerAsync = async () => {
const downloadResumable = FileSystem.createDownloadResumable(
{downloadUrl},
${FileSystem.documentDirectory}/pdf.pdf,
{},
);

const { uri, status } = await downloadResumable.downloadAsync();
// setSelectedImage({ localUri: uri });
Sharing.shareAsync(uri);
};

let openShareDialogAsync = async () => {
if (!(await Sharing.isAvailableAsync())) {
alert(Uh oh, sharing isn't available on your platform);
return;
}

Sharing.shareAsync(selectedImage.localUri);
};

// if (selectedImage !== null) {
// return (
// 
// 
// Share this
// 
// 
// );
// }

return (
<View style={{ flex: 1 }}>
<WebView
style={{ flex: 1 }}
source={{ uri: 'http://www.pdf995.com/' }}
onFileDownload={ ( { nativeEvent: { downloadUrl } } ) => {

        Alert.alert(
          "Documents",
          "Do you wish to download and share this document",
          [
            {
              text: "Download",
              onPress: () => {openImagePickerAsync}
            },
            {
              text: "Cancel",
              onPress: () => console.log("Cancel Pressed"),
              style: "cancel"
            },
          ],
          { cancelable: false }
        );}
      } />
      </View>
    );
  }

我从expo小吃中获取代码:https://snack.expo.io/@trinet/sharing 任何帮助将不胜感激。我真的卡住了

【问题讨论】:

  • 嗨,有趣,有错误吗?

标签: react-native expo react-native-webview


【解决方案1】:

我有同样的经历,在我的情况下,这是由于一些错误的标题配置,Content-Disposition inline 而不是附件,所以发生的事情是 inline 属性使它呈现网页中的内容而附件看到一个文件并尝试在不预览的情况下下载它。

将此添加到服务器上文件的标题配置中,您将成为文件。 感谢this SO answerthis

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-09-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多