我正在尝试将本地图像文件加载到浏览器中。代码不起作用。它总是为fileReader的结果返回零。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>
传递回调函数时不要使用()
。您不想称呼它,只需传递功能的地址即可。我花了一段时间也看到它。顺便说一句,在这方面,TransCrypt与JavaScript没有什么不同。还必须排除牙套。
请注意,您也可以简单地使用print()
而不是console.log()
。(但是在测试中,我也可能选择了console.log
来避免任何惊喜(
这有效:
#!/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()