尝试从一个html字段中上传一个excel文件以及一些其他信息,并将其存储到一个对象中,该对象将存储在序列化列表中。当前,网页响应输入,但是当我尝试按上载按钮时,它将解析为else语句“ failed”,例外消息为“ null”。
在我们切换到Thymeleaf之前,html只是临时的。
以下代码:
@MultipartConfig
@RestController
@RequestMapping(value = "/Teacher", produces = "text/html;charset=UTF-8")
public class Teacher {
TestController testcont;
@GetMapping("")
@ResponseBody
public String homePage(@RequestParam(value = "file", required = false) String name, HttpServletRequest request,
HttpServletResponse response){
StringBuilder sb = new StringBuilder();
sb.append("<p> <a href='/Teacher/NewTest'>New Test upload</a></p>\n"
+ "<p><a href='/SelectTest'>Select Test File</a> <button type='button'>Send Test</button></p>"
+ "\n \n \n"
+ "<p><a>Current Test for students:</a>\n <a href='/getCurrentTest'></a></p>"
);
return sb.toString();
}
@PostMapping
@RequestMapping("/NewTest")
@ResponseBody
public String newTestUpload(HttpServletRequest request, HttpServletResponse response){
StringBuilder sb = new StringBuilder();
if(!request.getParameterNames().hasMoreElements()){
sb.append("<p><form action='' method='post' enctype='multipart/form-data'>"
+ "<label>Enter file</label><input type='file' name='file'>"
+ "<button type='submit'>Upload</button></p>"
+ "<p><form action='/testName'>Test Name: <input type='text' name='name' value=''></p>"
+ "<p><form action='/addInfo'>Comment: <input type='text' comment='comment' value=''></p>"
+ "<p>Answer 1: <input type='text' Answer='answer1' value=''></p>"
+ "<p>Answer 2: <input type='text' Answer='answer2' value=''></p>"
+ "</form>"
+ "<a href='/Teacher'>Back</a>\n"
);
return sb.toString();
}
else if( request.getParameter("name") != ""
&& request.getParameter("comment") != "" && request.getParameter("answer1") != ""
&& request.getParameter("answer2") != ""){
try{
// Upload happens here
Part filePart = request.getPart("file");
String fileName = Paths.get(filePart.getSubmittedFileName()).getFileName().toString();
InputStream fileContent = filePart.getInputStream();
File testExcel = new File(fileName);
testExcel.createNewFile();
Files.copy(fileContent, Paths.get(testExcel.getName()), StandardCopyOption.REPLACE_EXISTING);
double ans1 = Double.parseDouble(request.getParameter("answer1"));
double ans2 = Double.parseDouble(request.getParameter("answer2"));
Test test = new Test(testExcel, request.getParameter("name"),
request.getParameter("comment"), ans1, ans2);
testcont.addTest(test);
sb.append("New test uploaded!<br/>\n<a href='/Teacher'>Back</a>\n");
return sb.toString();
} catch (Exception e){
sb.append("<h1>Couldnt insert test</h1>\n"
+ e.getMessage());
response.setStatus(HttpServletResponse.SC_OK);
return sb.toString();
}
}
else{
sb.append("failed<br/>\n<a href='/Teacher/NewTest'>Back</a>\n");
response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
return sb.toString();
}
}
}