Spaces:
Sleeping
Sleeping
come
commited on
Commit
·
9898ee7
1
Parent(s):
d2c4baa
Upload file.py
Browse files
file.py
ADDED
@@ -0,0 +1,48 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import os
|
2 |
+
|
3 |
+
import gradio as gr
|
4 |
+
import tempfile
|
5 |
+
import shutil
|
6 |
+
def generate_file(file_obj):
|
7 |
+
global tmpdir
|
8 |
+
print('临时文件夹地址:{}'.format(tmpdir))
|
9 |
+
print('上传文件的地址:{}'.format(file_obj.name)) # 输出上传后的文件在gradio中保存的绝对地址
|
10 |
+
|
11 |
+
#获取到上传后的文件的绝对路径后,其余的操作就和平常一致了
|
12 |
+
|
13 |
+
# 将文件复制到临时目录中
|
14 |
+
shutil.copy(file_obj.name, tmpdir)
|
15 |
+
|
16 |
+
# 获取上传Gradio的文件名称
|
17 |
+
FileName=os.path.basename(file_obj.name)
|
18 |
+
|
19 |
+
# 获取拷贝在临时目录的新的文件地址
|
20 |
+
NewfilePath=os.path.join(tmpdir,FileName)
|
21 |
+
print(NewfilePath)
|
22 |
+
|
23 |
+
# 打开复制到新路径后的文件
|
24 |
+
with open(NewfilePath, 'rb') as file_obj:
|
25 |
+
|
26 |
+
#在本地电脑打开一个新的文件,并且将上传文件内容写入到新文件
|
27 |
+
outputPath=os.path.join(tmpdir,"New"+FileName)
|
28 |
+
with open(outputPath,'wb') as w:
|
29 |
+
w.write(file_obj.read())
|
30 |
+
|
31 |
+
# 返回新文件的的地址(注意这里)
|
32 |
+
return outputPath
|
33 |
+
def main():
|
34 |
+
global tmpdir
|
35 |
+
with tempfile.TemporaryDirectory(dir='.') as tmpdir:
|
36 |
+
# 定义输入和输出
|
37 |
+
inputs = gr.components.File(label="上传文件")
|
38 |
+
outputs = gr.components.File(label="下载文件")
|
39 |
+
|
40 |
+
# 创建 Gradio 应用程序g
|
41 |
+
app = gr.Interface(fn=generate_file, inputs=inputs, outputs=outputs, title="文件上传、并生成可下载文件demo",
|
42 |
+
description="上传任何文件都可以,只要大小别超过你电脑的内存即可"
|
43 |
+
)
|
44 |
+
|
45 |
+
# 启动应用程序
|
46 |
+
app.launch(share=True)
|
47 |
+
if __name__=="__main__":
|
48 |
+
main()
|