1

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

根据 [ https://brython.info/][1]上的文档,我尝试读取一个文件,但它失败并出现此错误:访问 XMLHttpRequest at 'file:///C:/fakepath/requirements.txt'来自原点“ http://example.com:8000 ”的 CORS 策略已阻止:跨源请求仅支持以下协议方案:http、data、chrome、chrome-extension、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)

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

4

1 回答 1

3

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

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

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

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

最好选择文件type="file",但在这种情况下,该对象doc['rtfile1']是一个 FileList 对象,在DOM 的 Web API中描述,其第一个元素是一个 File 对象。不幸的是,阅读它的内容并不像 with 那样简单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)
于 2020-01-06T14:03:19.437 回答