Spaces:
Build error
Build error
| import streamlit as st | |
| import requests | |
| from tqdm import tqdm | |
| import os | |
| from urllib.parse import urlparse | |
| # 设置Streamlit应用程序的标题 | |
| st.title('文件下载器') | |
| # 创建一个文本输入框,让用户输入文件的URL | |
| url = st.text_input('输入文件的URL:') | |
| # 如果用户输入了URL并且点击了下载按钮 | |
| if st.button('下载'): | |
| if url: | |
| try: | |
| # 发送HEAD请求获取文件大小 | |
| response = requests.head(url, allow_redirects=True) | |
| file_size = int(response.headers.get('content-length', 0)) | |
| # 从URL中提取文件名 | |
| parsed_url = urlparse(url) | |
| filename = os.path.basename(parsed_url.path) | |
| if not filename: | |
| filename = 'downloaded_file' | |
| if len(filename) > 255: | |
| filename = filename[:255] | |
| # 下载文件并显示进度条 | |
| response = requests.get(url, stream=True) | |
| response.raise_for_status() # 如果发生HTTP错误,将引发异常 | |
| progress_bar = st.progress(0) | |
| downloaded_size = 0 | |
| chunk_size = 1024 # 每次读取1KB | |
| with open(filename, 'wb') as file: | |
| for data in tqdm(response.iter_content(chunk_size=chunk_size), | |
| total=file_size // chunk_size, unit='KB'): | |
| file.write(data) | |
| downloaded_size += len(data) | |
| progress_bar.progress(downloaded_size / file_size) | |
| st.success(f"文件已下载完成:{filename}") | |
| with open(filename, "rb") as file: | |
| st.download_button(label='下载文件', | |
| data=file, | |
| file_name=filename, | |
| mime='application/octet-stream') | |
| except requests.exceptions.RequestException as e: | |
| st.error(f"下载文件时出错:{e}") | |
| except Exception as e: | |
| st.error(f"发生错误:{e}") | |
| else: | |
| st.warning('请输入一个有效的URL。') | |