我试图使用spark框架和freemarker创建一个上传文件的方法,但我似乎在.getPart方法上遇到了一堵砖墙。我目前的freemarker代码如下:
<form method='post' enctype='multipart/form-data'>
<div>
<input type='file' name='uploadedFile'>
<button>Upload csv</button>
</div>
</form>
我的spark java post方法代码如下所示:
post(new Route("/pdf", "multipart/form-data") {
@Override
public Object handle(Request request, Response response) {
String name = null;
File upLoadM = new File("messages/");
Path tempFile = null;
Part file = null;
try {
tempFile = Files.createTempFile(upLoadM.toPath(), "", "");
System.out.println(tempFile);
}
catch (IOException e1) {
e1.printStackTrace();
}
request.attribute("org.eclipse.jetty.multipartConfig", new MultipartConfigElement("/temp"));
try {
file = request.raw().getPart("uploadedFile");
System.out.println(file);
}
catch (IOException | ServletException e1) {
e1.printStackTrace();
}
try (InputStream input = file.getInputStream()) {
Files.copy(input, tempFile, StandardCopyOption.REPLACE_EXISTING);
}
catch (IOException e) {
e.printStackTrace();
}
response.status(201);
response.redirect("/pdf");
return "";
}
});
当我点击上传按钮时,我收到500内部错误。不确定它在.getPart方法崩溃的原因是什么。任何帮助将不胜感激。
答案 0 :(得分:0)
事实证明,如果我调整一行代码就行了:
request.attribute("org.eclipse.jetty.multipartConfig", new MultipartConfigElement("/temp"));
到
request.attribute("org.eclipse.multipartConfig", new MultipartConfigElement("/temp"));