SpringBoot easily realizes file upload

Inscription:
Uploading files is very common in our functions. Programmers who are just beginning to contact may think that uploading files in Java is more complicated than PHP. Indeed, uploading files in PHP can be as simple as one sentence and does not require us to load functions ourselves. Packages, classes, etc., and java can be so complicated that writing a page of code may not complete the upload function. Of course, that is the way of IO stream, which belongs to the basic category of java. Today we use SpringBoot to realize the file upload function. , it can also be as simple as writing a sentence!

The following is an example of the file upload code:
1. Tool: IDEA

2. Create a SpringBoot web application

That is, when creating, only checkweb

(or

3. If you did nothing when you created it in the second step, all the way Next, then you only need the following content pom.xmlin your filedependencies

    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-web</artifactId>
    </dependency>

    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-test</artifactId>
        <scope>test</scope>
    </dependency>

)

4, the following is the upload code

    public void uploadFile( MultipartFile file) {

        try {

            String parentFile = "E:\\Workspace\\Temp\\file\\";

            File in = new File(parentFile + file.getOriginalFilename());

            File dest = in.getParentFile();

            if (!dest.exists()) //如果这个文件不存在
            {
                dest.mkdirs(); //创建
            }

            file.transferTo(in); // copy

            boolean isFileDelete = in.delete(); // delete file

            if (!isFileDelete) //删除失败
            {
                System.out.println("删除失败");
            }

        } catch (IOException e) {
            e.printStackTrace();
        }
    }

5. Calling example

    @RequestMapping(value = "/test")
    public String test(@RequestParam(value = "file") MultipartFile file) {

        uploadFile(file);

    }

postscript:

Is uploading files as simple as that?

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325445403&siteId=291194637