Skip to content

Instantly share code, notes, and snippets.

@zhangzhibin
Last active August 31, 2023 10:38
Show Gist options
  • Select an option

  • Save zhangzhibin/a21ec65b434f45efec2103f03b29ba57 to your computer and use it in GitHub Desktop.

Select an option

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/
// 影子工作室为你提供详细步骤 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);
}
}
@zhangzhibin
Copy link
Copy Markdown
Author

@stars66
Copy link
Copy Markdown

stars66 commented Dec 1, 2021

It's not working on iOS safari.

@zhangzhibin
Copy link
Copy Markdown
Author

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