以下代码提示用户选择本地存储库中的文件,输入一些输入字段,然后将文件上传到服务器。当前,它将由createTempFile创建它存储在/ tmp文件夹中。成功创建文件,并根据业务案例的需要创建对该文件的引用的对象。是的!
但是,我想将所有文件存储在服务器存储库中一个单独且可组织的文件夹中,例如“ / uploadedFiles”。
我尝试了几种方法,从在存储库文件夹中创建一个空文件,然后尝试对其进行覆盖,再到将上传的文件复制到该文件夹中。到目前为止,似乎没有任何容易解决的方法都无法奏效,除非我错过了明显的事情(我可能这样做了)。
所有创建的文件的文件扩展名后均带有长数字序列,例如“ testfile.xls1612634232432”;这是从inputstream的缓冲区中获取的吗?
下面的代码是当前的工作方式,只需将上传的文件写入/ tmp目录中的临时文件即可。我需要将其保存到我选择的任何其他目录中,然后将其合格地传递给对象构造函数。
该方法从newTestUpload开始。
@MultipartConfig
@RestController
@RequestMapping(value = "/Teacher", produces = "text/html;charset=UTF-8")
public class Teacher {
TestController testcont = TestController.getInstance();
@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();
try {
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 {
// This is where the magic happens
Part filePart = request.getPart("file");
String fileName = Paths.get(filePart.getSubmittedFileName()).getFileName().toString();
InputStream fileContent = filePart.getInputStream();
byte[] buffer = new byte[fileContent.available()];
fileContent.read(buffer);
File testExcel = File.createTempFile(fileName, "", null);
OutputStream outStream = new FileOutputStream(testExcel);
outStream.write(buffer);
// 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"),
request.getParameter("answer1"), request.getParameter("answer2"));
testcont.addTest(test);
testExcel.deleteOnExit();
outStream.close();
sb.append("New test uploaded!<br/>\n<a href='/Teacher'>Back</a>\n" + testExcel.getPath()
+ "<p>_________</p>" + test.getFile().getPath());
return sb.toString();
} catch (Exception e) {
sb.append("<h1>Couldnt insert test</h1>\n" + e.getMessage() + e.getStackTrace() + e.getCause());
response.setStatus(HttpServletResponse.SC_OK);
e.printStackTrace();
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();
}
} catch (Exception e) {
e.printStackTrace();
}
return "";
}
}
答案 0 :(得分:0)
不要创建临时文件,而是在要创建的目录中创建文件。
OutputStream outStream = new FileOutputStream(new File("<fileName>"));
如果要先创建不包含数据的文件。您可以使用下面的代码,如果尚未创建,它将创建目录:
public static void saveToFile(String folderPath, String fileName) throws IOException {
File directory = new File(folderPath);
if (!directory.exists() && !directory.mkdirs()) {
throw new IOException("Directory does not exist and could not be created");
}
String filePath = folderPath + File.separator + fileName;
File theFile = new File(filePath);
if (!theFile.exists()) {
try {
theFile.createNewFile();
} catch (IOException e) {
throw new IOException("Facing issues in creating file " + filePath, e);
}
}
}
答案 1 :(得分:0)
File testExcel = File.createTempFile(fileName, "", null);
替换为:
File testExcel = new File("/tests/", fileName);
testExcel.getParentFile().mkdirs();
成功了!现在就像魅力一样。