2

我正在尝试将本地图像文件加载到浏览器中。代码不起作用。对于 Filereader 的结果,它总是返回 null。read_file3.py 的代码:

#!/usr/bin/env python
# -*- coding: utf-8 -*-

class TestSystem:

    def openFile(self, event):
        self.inputvar = event.target
        console.log("self.inputvar"+self.inputvar)
        console.log("self.inputvar.files[0]"+self.inputvar.files[0])
        self.freader = __new__(FileReader())
        self.freader.onload = self.processInput()
        self.freader.readAsDataURL(self.inputvar.files[0])

    def processInput(self):
        dataURL = self.freader.result
        console.log("type:"+type(dataURL))
        console.log("dataURL:"+dataURL)
        document.getElementById('output').src = dataURL

testSystem = TestSystem()

和html:

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="utf-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <script src="__javascript__/read_file3.js"; charset="UTF-8"></script>
    <title>Read local image File</title>
  </head>
  <body>
    <main>
        <h1>Read a local image file!</h1>
        <p id="p1" class="para1">Read a local image file!</p>
      <input type='file' accept='image/*' onchange='read_file3.testSystem.openFile(event)'><br>
      <img id='output'>
      <p id="demo"></p>
    </main>
  </body>
</html>
4

1 回答 1

2

Don't use () when you pass a callback function. You don't want to call it, just pass the address of the function. Took me a while to see it as well. By the way, Transcrypt is no different from JavaScript in this respect. There also the braces would have to be left out.

Note that you can also simply use print() instead of console.log(). (But in a test I may also have opted for console.log to avoid any surprises)

This works:

#!/usr/bin/env python
# -*- coding: utf-8 -*-

class TestSystem:

    def openFile(self, event):
        self.inputvar = event.target
        console.log("self.inputvar"+self.inputvar)
        console.log("self.inputvar.files[0]"+self.inputvar.files[0])
        self.freader = __new__(FileReader())

        self.freader.onload = self.processInput
        # No braces, since you don't want to call this function
        # but just pass its address...

        self.freader.readAsDataURL(self.inputvar.files[0])

    def processInput(self):
        dataURL = self.freader.result
        console.dir (self.freader)
        console.log("type:"+type(dataURL))
        console.log("dataURL:"+dataURL)
        document.getElementById('output').src = dataURL
        console.dir (self.freader)

testSystem = TestSystem()
于 2018-02-22T12:03:59.813 回答