我想使用react来将文件上传到服务器,因为我正在使用fileReader接口,但是在任何浏览器中均未触发任何事件(onload,onprogress)。我需要req.file中的文件,因为我正在使用expressJS作为后端(multer)来保存文件,multer不会保存在req.body中。
我尝试了几种解决方案,但都没有用
jsx
<form onSubmit={(event) => handleFileUpload(event)}>
<input type="file" ref={(ref) => { this.uploadInput = ref; }} />
<div>
<Button type="Submit"><CloudUpload /></Button>
</div>
</form>
javascript
function handleFileUploadHelper(payload,getState) {
payload.preventDefault();
const file = payload.target.elements[0].files;
if(file.length > 0) {
const reader = new FileReader();
reader.onload = ((event) => {
const formData = new FormData();
formData.append('file', event.target.result.split(',')[1]);
const resp = post('/api/resources/upload', formData); // post uses fetch API
})
reader.onerror = (event) => console.log(event);
reader.onabort = (event) => console.log(event);
reader.onprogress = (event) => console.log(event);
}
}
既不调用API也不安慰消息