【发布时间】:2018-08-19 21:32:10
【问题描述】:
我正在 React 中构建一个拼图应用程序,允许用户上传他们自己的拼图。这在网络上运行良好(用户单击输入的标签并打开一个对话框。当用户选择一个文件时,onChange 事件被触发),但在移动设备上,或者至少在 Android 上的 Chrome 上,文件不是读...
这是声明输入的地方:
<div className="file-input-wrapper">
<label for="puzzleUpload" className="button-dark">Upload Puzzle(s)</label>
<input type="file"
accept="application/json"
multiple
id="puzzleUpload"
onChange={handleFiles}/>
</div>
这就是handleFiles() 方法
// when a file is uploaded, this checks to see that it's the right type, then adds it to the puzzle list
const handleFiles = () => {
var selectedFiles = document.getElementById('puzzleUpload').files;
// checks if the JSON is a valid puzzle
const validPuzzle = (puzzle) => {
let keys = ["name", "entitySetID", "logic", "size"];
return keys.every((key) => {return puzzle.hasOwnProperty(key)});
};
const onLoad = (event) => {
let puzzle = JSON.parse(event.target.result);
if(validPuzzle(puzzle)) {
appendPuzzleList(puzzle);
}
else {
console.log("JSON file does not contain a properly formatted Logike puzzle")
}
};
//checks the file type before attempting to read it
for (let i = 0; i < selectedFiles.length; i++) {
if(selectedFiles[i].type === 'application/json') {
//creates new readers so that it can read many files sequentially.
var reader = new FileReader();
reader.onload = onLoad;
reader.readAsText(selectedFiles[i]);
}
}
};
可以在http://logike.confusedretriever.com 找到具有最新代码的工作原型,并且可以使用应用中的构建器快速编写兼容的 JSON。
过去一个半小时我一直在寻找解决方案,但空手而归,因此我们将不胜感激!我阅读了 FileReader 文档,似乎所有内容都受支持,所以我有点难过。
有趣的是,文件被选中(一旦选中,您可以在输入的丑陋默认版本中看到文件名,但我通过 CSS 将其隐藏),所以我很想实现一个仅限移动设备的按钮来触发事件,如果没有更合法的解决方案...
【问题讨论】:
标签: javascript reactjs input