Last active
August 31, 2023 10:38
-
-
Save zhangzhibin/a21ec65b434f45efec2103f03b29ba57 to your computer and use it in GitHub Desktop.
Using Open File Dialog in Cocos Creator project 详细步骤参考 https://xmanyou.com/cocos-creator-open-file-box/
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 影子工作室为你提供详细步骤 https://xmanyou.com/cocos-creator-open-file-box/ | |
const {ccclass, property} = cc._decorator; | |
@ccclass | |
export default class FileBox extends cc.Component { | |
// LIFE-CYCLE CALLBACKS: | |
@property | |
containerId = "_filebox_container_"; | |
@property | |
inputBoxId = "_filebox_input_"; | |
inputBox = null; | |
start () { | |
this.initInputBox(); | |
} | |
initInputBox(){ | |
let inputBox = this.getInputBox(this.inputBoxId, this.containerId); | |
if(inputBox){ | |
inputBox.onchange = (evt)=>{ | |
console.info("===> input value change: ", evt); | |
const fileList = evt.target.files; | |
console.info("===> file list: ", fileList); | |
console.info("===> value: ", inputBox.value); | |
let file = fileList[0]; | |
if(!file){ | |
console.info("===> No file selected"); | |
return; | |
} | |
this.readFile(file); | |
}; | |
}else{ | |
console.warn("Can't get or create input box"); | |
} | |
} | |
getInputBox(inputBoxId:string, containerId:string){ | |
if(!this.inputBox){ | |
let inputBox = document.getElementById(inputBoxId) as HTMLInputElement; | |
if(!inputBox){ | |
let container = document.getElementById(containerId); | |
if(!container){ | |
container = document.createElement('div'); | |
document.body.appendChild(container); | |
container.id = containerId; | |
} | |
inputBox = document.createElement("input") as HTMLInputElement; | |
inputBox.id = inputBoxId; | |
inputBox.type = "file"; | |
container.appendChild(inputBox); | |
} | |
this.inputBox = inputBox; | |
} | |
return this.inputBox; | |
} | |
onClick(){ | |
if(this.inputBox){ | |
console.info("click start"); | |
this.inputBox.click(); | |
console.info("click done") | |
} | |
} | |
readFile(fileUrl){ | |
let reader = new FileReader(); | |
reader.onload = function(e) { | |
let content = e.target.result; | |
// Display file content | |
console.info("===> file content: ", content); | |
}; | |
// 这里用文本方式读,也可以用别的方式 | |
reader.readAsText(fileUrl); | |
} | |
} |
It's not working on iOS safari.
OK...I only tested on Chrome on my MacOS.
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
《Cocos Creator 项目中如何使用系统的文件选择对话框?》