我正在前端使用React Typescript,后端使用Spring Boot。
对于前端,我有一个主页,其中设置了文件上传表单:
export const Home: React.FC = () => {
return (
<div className="input-container">
<form className="form-wrapper" action={"/upload"} method={"POST"} encType="multipart/form-data">
<button className="choose-file" type="button">
Choose File
<input className="file-input" type="file" name="file" accept={".csv"}/>
</button>
<button className="upload-button" type="submit">
Submit
</button>
</form>
</div>
)
};
文件的模型:
public class File {
private long id;
private float lat;
private float log;
// getters and setters
}
解析CSV文件的spring控制器:
@Controller
@CrossOrigin("http://localhost:8080")
public class FileController {
@GetMapping("/")
public String home() {
return "index";
}
@PostMapping("/upload")
public String GetFile(@RequestParam("file") MultipartFile file, Model model) {
//validate file
if (file.isEmpty()) {
model.addAttribute("message", "No File Selected, Select CSV file to upload");
model.addAttribute("status", false);
} else {
// parse CSV file to create a table
try (Reader reader = new BufferedReader((new InputStreamReader(file.getInputStream())))) {
// create csv bean reader
CsvToBean<File> csvToBean = new CsvToBeanBuilder(reader)
.withType(File.class)
.withIgnoreLeadingWhiteSpace(true)
.build();
// convert CSVbean to table list
List<File> files = csvToBean.parse();
// TODO: save file list into db
// save file list on model
model.addAttribute("files", files);
model.addAttribute("status", true);
} catch (Exception e){
model.addAttribute("message", "An error occurred while processing the CSV file.");
model.addAttribute("status", false);
}
}
return file;
}
}
现在,当我选择一个文件并单击“提交”按钮时,我收到一条消息,提示:
“无法发布/上传”
如何解决此问题并使其正确路由并显示文件内容?谢谢。