You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Gradio中获取上传文件的路径并存入变量?

如何在Gradio中获取并存储上传文件的路径

你可以通过以下几种方式将上传文件的路径存储到变量中,根据场景选择合适方案:

方案1:使用全局变量(简单单用户场景)

直接在函数外部定义全局变量,在upload_file函数内更新这个变量的值:

import gradio as gr

# 定义全局变量存储文件路径
uploaded_file_paths = []

def upload_file(files):
    global uploaded_file_paths
    file_paths = [file.name for file in files]
    # 将路径赋值给全局变量
    uploaded_file_paths = file_paths
    return file_paths

with gr.Blocks() as demo:
    file_output = gr.File()
    opt = gr.Label()
    upload_button = gr.UploadButton("Click to Upload a File", file_types=["image", "video"], file_count="multiple")
    upload_button.upload(upload_file, upload_button, file_output)

demo.launch()

后续可在代码其他位置直接调用uploaded_file_paths获取已上传文件路径。注意:全局变量在多用户同时使用时会被覆盖,仅适合单用户测试或简单场景。

方案2:使用类维护状态(多用户/复杂场景)

如果应用需要支持多用户或复杂状态管理,用类封装状态可避免全局变量的冲突问题:

import gradio as gr

class FileUploadState:
    def __init__(self):
        self.uploaded_paths = []
    
    def upload_file(self, files):
        file_paths = [file.name for file in files]
        self.uploaded_paths = file_paths
        return file_paths

# 实例化状态类
state = FileUploadState()

with gr.Blocks() as demo:
    file_output = gr.File()
    opt = gr.Label()
    upload_button = gr.UploadButton("Click to Upload a File", file_types=["image", "video"], file_count="multiple")
    # 绑定类中的方法
    upload_button.upload(state.upload_file, upload_button, file_output)

demo.launch()

后续通过state.uploaded_paths即可获取存储的文件路径,这种方式每个用户的状态相互独立,适合生产环境的多用户场景。

内容的提问来源于stack exchange,提问作者user1112259

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.23 22:22:49