Transcrypt and FileReader

点点圈 提交于 2019-12-24 01:56:13

问题


I am trying to load a local image file into the browser. The code doesn't work. It always returns null for the result of the Filereader. The code for 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()

and the 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>

回答1:


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()


来源:https://stackoverflow.com/questions/48851822/transcrypt-and-filereader

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!