I try to read Enum (as a response), sending from server (Spring) to client (React) during downloading a file to the DB. But no matter how hard I try, I couldn't read it. My max success was when I use typeof - I got "string":
Here is how I treat the response on client:
export default function File() {
const [selectedFile, setSelectedFile] = useState('');
const [isFileSelected, setIsFileSelected] = useState(false);
const [answer, setAnswer] = useState('');
const fileSelectedHandler = event => {
setSelectedFile(event.target.files[0]);
setIsFileSelected(true);
setAnswer("File is ready for downloading");
};
function getValue(answer) {
console.log("the result of typeof is: " + typeof answer);
switch (answer) {
case 'SUCCESS':
return "One result";
case 'CHECK_FILE_EXTENSION':
return "Second result";
case 'FILE_ALREADY_EXISTS':
return "Third result";
default:
return "File not chosen";
}
}
const fileUploadHandler = () => {
if (isFileSelected === true) {
const formData = new FormData();
formData.append("file", selectedFile);
fetch("/api/upload", {
method: 'POST',
body: formData
})
.then(response => response.text())
.then(response => setAnswer(getValue(response)))
} else {
setAnswer('File not chosen');
}
};
return (
<div align="center">
<table>
<tr>
<td>Выберите файл:</td>
<td><input type="file" onChange={fileSelectedHandler}/></td>
</tr>
<tr>
<td></td>
<td>
<button onClick={fileUploadHandler}>Загрузить</button>
</td>
</tr>
</table>
<td>
<h1>{answer}</h1>
</td>
</div>
);
}
Here is my Enum on server:
public enum DownloadStatus {
FILE_ALREADY_EXISTS,
SUCCESS,
CHECK_FILE_EXTENSION;
}
Here is a method:
public Enum <DownloadStatus> checkFileNameBeforeUploadToDB (File fileName) throws IOException {
String fileExtension = getExtension(fileName.getPath());
if ((fileExtension.equals("xlsx")) || (fileExtension.equals("xls"))) {
if (isFileNameExistInList(getAll(), fileName)) {
return DownloadStatus.FILE_ALREADY_EXISTS;
} else {
addNewFile(fileName);
return DownloadStatus.SUCCESS;
}
} else {
return DownloadStatus.CHECK_FILE_EXTENSION;
}
}
Here is a controller:
@RequestMapping(value = "/api/upload", method = RequestMethod.POST)
@ResponseBody
public Enum<DownloadStatus> uploadFile(@RequestParam("file") MultipartFile multiPartFile) throws IOException, JSONException, NullPointerException {
File file = convertFromMultipartToFile(multiPartFile);
return fireService.checkFileNameBeforeUploadToDB(file);
}
Where is my mistake?
Thanks is advance :-)
question from:
https://stackoverflow.com/questions/65903672/cant-read-enum-from-server-spring-on-react 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…