Ethscriptions commited on
Commit
9aaf9d7
·
verified ·
1 Parent(s): a2714e5

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +28 -14
app.py CHANGED
@@ -1,6 +1,7 @@
1
  import streamlit as st
2
  import requests
3
- from io import BytesIO
 
4
 
5
  # 设置Streamlit应用程序的标题
6
  st.title('文件下载器')
@@ -12,22 +13,35 @@ url = st.text_input('输入文件的URL:')
12
  if st.button('下载'):
13
  if url:
14
  try:
15
- # 发送HTTP GET请求以下载文件
16
- response = requests.get(url)
17
- response.raise_for_status() # 如果发生HTTP错误,将引发异常
18
-
19
  # 从URL中提取文件名
20
  filename = url.split('/')[-1]
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
21
 
22
- # 创建一个字节流对象
23
- file = BytesIO(response.content)
24
-
25
- # 提供文件下载
26
- st.download_button(label='下载文件',
27
- data=file,
28
- file_name=filename,
29
- mime='application/octet-stream')
30
- st.success(f"文件已准备好下载:{filename}")
31
  except requests.exceptions.RequestException as e:
32
  st.error(f"下载文件时出错:{e}")
33
  else:
 
1
  import streamlit as st
2
  import requests
3
+ from tqdm import tqdm
4
+ import os
5
 
6
  # 设置Streamlit应用程序的标题
7
  st.title('文件下载器')
 
13
  if st.button('下载'):
14
  if url:
15
  try:
16
+ # 发送HEAD请求获取文件大小
17
+ response = requests.head(url, allow_redirects=True)
18
+ file_size = int(response.headers.get('content-length', 0))
19
+
20
  # 从URL中提取文件名
21
  filename = url.split('/')[-1]
22
+
23
+ # 下载文件并显示进度条
24
+ response = requests.get(url, stream=True)
25
+ response.raise_for_status() # 如果发生HTTP错误,将引发异常
26
+
27
+ progress_bar = st.progress(0)
28
+ downloaded_size = 0
29
+ chunk_size = 1024 # 每次读取1KB
30
+
31
+ with open(filename, 'wb') as file:
32
+ for data in tqdm(response.iter_content(chunk_size=chunk_size),
33
+ total=file_size // chunk_size, unit='KB'):
34
+ file.write(data)
35
+ downloaded_size += len(data)
36
+ progress_bar.progress(downloaded_size / file_size)
37
 
38
+ st.success(f"文件已下载完成:{filename}")
39
+ with open(filename, "rb") as file:
40
+ st.download_button(label='下载文件',
41
+ data=file,
42
+ file_name=filename,
43
+ mime='application/octet-stream')
44
+
 
 
45
  except requests.exceptions.RequestException as e:
46
  st.error(f"下载文件时出错:{e}")
47
  else: