简体   繁体   English

Spring Boot-将文件上传到服务器

[英]Spring Boot - Upload file to server

The code belows prompts a user to select a file on his local repository, enter some input fields and then upload the file to a server. 以下代码提示用户选择本地存储库中的文件,输入一些输入字段,然后将文件上传到服务器。 Currently, it will store it in a /tmp folder, as it is created by createTempFile. 当前,它将由createTempFile创建它存储在/ tmp文件夹中。 The file is successfully created, and an object is created with a reference to that file as needed by the business case. 成功创建文件,并根据业务案例的需要创建对该文件的引用的对象。 Yay! 好极了!

However, I want to store all files in a seperate and organizable folder like "/uploadedFiles" on the server repository. 但是,我想将所有文件存储在服务器存储库中一个单独且可组织的文件夹中,例如“ / uploadedFiles”。

  1. I have tried several things, from creating an empty file on the repository folder and then attempting an overwrite on to it, to just copying the uploaded file to the folder. 我尝试了几种方法,从在存储库文件夹中创建一个空文件,然后尝试对其覆盖,再到将上传的文件复制到该文件夹​​中。 None of what seemed to be easy fixes worked so far, unless I missed something obvious (which I probably did). 到目前为止,似乎没有容易解决的问题都无法奏效,除非我错过了明显的事情(我可能这样做了)。

  2. The files created all have a long sequence of numbers after the file extension in their names, like "testfile.xls1612634232432"; 所有创建的文件的文件扩展名后均带有一长串数字,例如“ testfile.xls1612634232432”; is this from the buffer of the inputstream? 这是从inputstream的缓冲区获取的吗?

The code below is how it currently works, with just writing the uploaded file to a temp file in the /tmp directory. 下面的代码是当前的工作方式,只需将上传的文件写入/ tmp目录中的临时文件即可。 I need to get it to any other directory of my choosing, and then eligibly pass it to the object constructor. 我需要将其保存到我选择的任何其他目录中,然后将其合格地传递给对象构造函数。

The method begins at newTestUpload. 该方法从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 "";

    }

}

Instead of creating a temp file, create file in the directory that you want to create. 而不是创建临时文件,而是在要创建的目录中创建文件。

OutputStream outStream = new FileOutputStream(new File("<fileName>"));

If you want to create file first without data. 如果要先创建没有数据的文件。 you can use below code, it will create directory as well if not already created: 您可以使用以下代码,如果尚未创建目录,它也会创建目录:

    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);
            }
        }
    }
File testExcel = File.createTempFile(fileName, "", null);

replaced with: 替换为:

File testExcel = new File("/tests/", fileName);
testExcel.getParentFile().mkdirs();

did the trick! 做到了! Works like a charm now. 现在就像魅力一样。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM