【问题标题】:File reading not working in Brython/Python文件读取在 Brython/Python 中不起作用
【发布时间】:2020-01-04 14:10:58
【问题描述】:

我的要求:从 ID = "rtfile1" 的输入 type="file" 读取内容并将其写入 ID- "rt1" 的 textarea

根据 [https://brython.info/][1] 上的文档,我尝试读取文件,但失败并出现以下错误: 从源“http://example.com:8000”访问“file:///C:/fakepath/requirements.txt”处的 XMLHttpRequest 已被 CORS 策略阻止:跨源请求仅支持协议方案:http、data、chrome、chrome -扩展,https。

我尝试了两个 Brython 代码,它们都因上述相同的错误而失败。

代码1:

def file_read(ev):
    doc['rt1'].value = open(doc['rtfile1'].value).read()
doc["rtfile1"].bind("input", file_read)

代码 2:

 def file_read(ev):
    def on_complete(req):
        if req.status==200 or req.status==0:
            doc['rt1'].value = req.text
        else:
            doc['rt1'].value = "error "+req.text

    def err_msg():
        doc['rt1'].value = "server didn't reply after %s seconds" %timeout

    timeout = 4

    def go(url):
        req = ajax.ajax()
        req.bind("complete", on_complete)
        req.set_timeout(timeout, err_msg)

        req.open('GET', url, True)

        req.send()
    print('Triggered')
    go(doc['rtfile1'].value)

doc["rtfile1"].bind("input", file_read)

任何帮助将不胜感激。谢谢!!! :)

【问题讨论】:

    标签: python brython


    【解决方案1】:

    这与 Brython 无关(使用等效的 Javascript 会得到相同的结果),而是与您告诉浏览器要上传哪个文件的方式有关。

    如果您通过 HTML 标记选择文件,例如

    <input type="file" id="rtfile1">
    

    Brython 代码中doc['rtfile1'] 引用的对象有一个属性value,但它不是文件路径或url,它是浏览器构建的“假路径”(如你可以在错误消息中看到),并且不能将其用作 Brython 函数open() 的参数,也不能用作发送 Ajax 请求的 url;如果你想使用文件 url,你应该在一个基本的输入标签中输入它(不带type="file")。

    最好选择带有type="file" 的文件,但在这种情况下,对象doc['rtfile1'] 是一个FileList 对象,在DOM's Web API 中进行了描述,其第一个元素是一个File 对象.不幸的是,阅读其内容并不像 open() 那样简单,但这里有一个工作示例:

    from browser import window, document as doc
    
    def file_read(ev):
    
        def onload(event):
            """Triggered when file is read. The FileReader instance is
            event.target.
            The file content, as text, is the FileReader instance's "result"
            attribute."""
            doc['rt1'].value = event.target.result
    
        # Get the selected file as a DOM File object
        file = doc['rtfile1'].files[0]
        # Create a new DOM FileReader instance
        reader = window.FileReader.new()
        # Read the file content as text
        reader.readAsText(file)
        reader.bind("load", onload)
    
    doc["rtfile1"].bind("input", file_read)
    

    【讨论】:

      猜你喜欢
      • 2014-11-17
      • 2018-09-10
      • 2011-03-05
      • 1970-01-01
      • 1970-01-01
      • 2014-04-17
      • 1970-01-01
      • 1970-01-01
      • 2014-07-26
      相关资源
      最近更新 更多