跳到主要内容

Input Button Ajax

2024年10月17日
柏拉文
越努力,越幸运

一、认识


二、语法


function Test(props) {
const { useRef } = React;
const inputRef = useRef(null);
const buttonStyle = {
display: "inline-block",
padding: "4px 6px",
borderRadius: "3px",
backgroundColor: "#25c2a0",
cursor: "pointer"
}

const onUploadFile = (file)=>{
const ajax = new XMLHttpRequest();
ajax.open("post", "http://localhost:4000/upload", true);
ajax.onreadystatechange = () => {
if (ajax.readyState === 4 && [200, 304].includes(ajax.status)) {
const { response } = ajax;
console.log(response);
}
};
const formData = new FormData();
formData.append("file", file);
formData.append("operator", "柏拉图");
formData.append("filename", file.name);
ajax.send(formData);
}
const onChooseFile = (event)=>{
const { files } = event.target;
const [file] = files;
onUploadFile(file);
}
const onUploadButtonHandle = ()=>{
if (inputRef.current) {
inputRef.current.click();
}
}


return (
<div>
<input
type="file"
name="file"
accept="xlsx"
ref={inputRef}
onChange={ onChooseFile }
style={{ display: 'none' }}
/>
<div style={ buttonStyle } onClick={ onUploadButtonHandle }>上传文件</div>
</div>
);
}