如何在react native中从flask下载文件

rqqzpn5f  于 2023-02-16  发布在  React
关注(0)|答案(1)|浏览(148)

我正在做一个从youtube下载视频的小程序,我用react native做前端,用python flask做后端,下面是服务器端的代码,它把视频下载到服务器端,然后作为附件返回给客户端

from flask import Flask, send_file
import vid_request

app = Flask(__name__)

@app.route("/<url>")
def download(url):
    path = vid_request.download(url, r"\tempDownloads")
    return send_file(path, as_attachment=True)

if __name__ == "__main__":
    app.run(host="0.0.0.0")

//视频请求文件

import pytube

def download(url, path):
    url = "https://www.youtube.com/watch?v="+url
    youtubeObject = pytube.YouTube(url).streams.filter(only_audio=True).first()
    out_file = youtubeObject.download(output_path=path)

    return out_file

当我进入url并输入youtube链接时,这个方法有效,但是当我从react native使用这个方法时

await fetch(`http://192.168.0.12:5000/${input}`);

它不工作,并给出一个错误,是否有一个更好的方式发送文件在服务器端,或更好的方式从客户端下载?

zpqajqem

zpqajqem1#

  1. npx expo install expo-file-system
    1.如果是纯React Native,您还需要执行以下步骤:https://github.com/expo/expo/tree/sdk-47/packages/expo-file-system
    1.修改如下
import { downloadAsync, documentDirectory} from 'expo-file-system';
import { Button, View } from 'react-native';

export default function App() {
  const download = async () => {
    console.log("downloading");
    const { uri: localUri } = await downloadAsync('http://192.168.0.12:5000/video.mp4', documentDirectory + 'video.mp4');
    console.log("download complete. File "+localUri);
  }
  return (
    <View style={{flex:1, alignItems: "center", justifyContent: "center"}}>
      <Button title="download" onPress={download}></Button>
    </View>
  );
}

Full Documentation

相关问题