springboot文件上传

x33g5p2x  于2021-09-25 转载在 Spring  
字(9.3k)|赞(0)|评价(0)|浏览(385)

1.pom.xml

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.5.4</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>
    <groupId>com.yl</groupId>
    <artifactId>fileupload</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <name>fileupload</name>
    <description>Demo project for Spring Boot</description>
    <properties>
        <java.version>1.8</java.version>
    </properties>
    <dependencies>
        <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>
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>

</project>

2.文件上传的配置

# 文件上传的配置
# 是否开启文件上传功能,默认开启
spring.servlet.multipart.enabled=true
# 文件大小
spring.servlet.multipart.max-file-size=2MB
# 文件大小超过多少时就往缓存里面放
spring.servlet.multipart.file-size-threshold=3MB
# 文件保存的临时位置
spring.servlet.multipart.location=
# 最大的请求大小
spring.servlet.multipart.max-request-size=10MB
# 是否开启延迟解析
spring.servlet.multipart.resolve-lazily=false

3.单文件上传

3.1 html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<form action="/upload" method="post" enctype="multipart/form-data">
    <input type="file" name="file">
    <input type="submit" value="上传">
</form>
</body>
</html>

3.2 controller

package com.yl.fileupload.controller;

import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.UUID;

/** * 单文件上传 */
@RestController
public class FileUploadController {
    SimpleDateFormat sdf = new SimpleDateFormat("/yyyy/MM/dd/");

    @PostMapping("/upload")
    public String upload(MultipartFile file, HttpServletRequest request) {
        String s = sdf.format(new Date());
        String path = "D:\\fileUpload" + s;
        File folder = new File(path);
        if (!folder.exists()) {
            folder.mkdirs();
        }
        //旧文件名
        String oldName = file.getOriginalFilename();
        //新文件名
        String newName = UUID.randomUUID().toString() + oldName.substring(oldName.lastIndexOf("."));
        //上传文件
        try {
            file.transferTo(new File(folder,newName));
            String s1 = request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort() + s + newName;
            return s1;
        } catch (IOException e) {
            e.printStackTrace();
        }
        return "";
    }

}

4.多文件一起上传

4.1 html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<form action="/upload2" method="post" enctype="multipart/form-data">
    <input type="file" name="files" multiple>
    <input type="submit" value="上传">
</form>
</body>
</html>

4.2 controller

package com.yl.fileupload.controller;

import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.UUID;

/** * 多文件上传 */
@RestController
public class FileUploadController2 {
    SimpleDateFormat sdf = new SimpleDateFormat("/yyyy/MM/dd/");

    @PostMapping("/upload2")
    public String upload(MultipartFile[] files, HttpServletRequest request) {
        String realPath = request.getServletContext().getRealPath("/");
        String s = sdf.format(new Date());
        String path = realPath + s;
        File folder = new File(path);
        if (!folder.exists()) {
            folder.mkdirs();
        }
        try {
            String finalStr = "";
            for (MultipartFile multipartFile : files) {
                //旧文件名
                String oldName = multipartFile.getOriginalFilename();
                //新文件名
                String newName = UUID.randomUUID().toString() + oldName.substring(oldName.lastIndexOf("."));
                //上传文件
                multipartFile.transferTo(new File(folder,newName));
                String s1 = request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort() + s + newName;
                finalStr += s1 + ";";
            }
            return finalStr;
        } catch (IOException e) {
            e.printStackTrace();
        }
        return "";
    }

}

5.多文件分开上传

5.1 html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<form action="/upload3" method="post" enctype="multipart/form-data">
    <input type="file" name="file1">
    <input type="file" name="file2">
    <input type="submit" value="上传">
</form>
</body>
</html>```

## 5.1 controller

```java
package com.yl.fileupload.controller;

import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.UUID;

/** * 单文件上传 */
@RestController
public class FileUploadController3 {
    SimpleDateFormat sdf = new SimpleDateFormat("/yyyy/MM/dd/");

    @PostMapping("/upload3")
    public String upload(MultipartFile file1,MultipartFile file2, HttpServletRequest request) {
        String realPath = request.getServletContext().getRealPath("/");
        String s = sdf.format(new Date());
        String path = realPath + s;
        File folder = new File(path);
        if (!folder.exists()) {
            folder.mkdirs();
        }
        try {
            String finalStr = "";
            //旧文件名
            String oldName1 = file1.getOriginalFilename();
            //新文件名
            String newName1 = UUID.randomUUID().toString() + oldName1.substring(oldName1.lastIndexOf("."));
            //上传文件
            file1.transferTo(new File(folder,newName1));
            String s1 = request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort() + s + newName1;
            //旧文件名
            String oldName2 = file2.getOriginalFilename();
            //新文件名
            String newName2 = UUID.randomUUID().toString() + oldName2.substring(oldName2.lastIndexOf("."));
            //上传文件
            file2.transferTo(new File(folder,newName2));
            String s2 = request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort() + s + newName2;
            finalStr = s1 + ";" + s2;
            return finalStr;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "";
    }

}

6.借用ajax上传

6.1 html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <!--引入jq-->
    <script src="https://code.jquery.com/jquery-3.6.0.js" integrity="sha256-H+K7U5CnXl1h5ywQfKtSj8PCmoN9aaq30gDh27Xc0jk=" crossorigin="anonymous"></script>
</head>
<body>
<div id="app" ></div>
<input type="file" id="file"/>
<input type="button" value="上传文件" onclick="uploadFile()">
<script>
    function uploadFile() {
        var file = $("#file")[0].files[0];
        var formData = new FormData();
        formData.append("file",file);
        formData.append("name","yl");
        $.ajax({
            type: 'post',
            url: '/upload',
            processData: false,
            contentType: false,
            data: formData,
            success: function(msg) {
                $("#app").html(msg)
            }
        })
    }
</script>
</body>
</html>

6.2 controller

package com.yl.fileupload.controller;

import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.UUID;

/** * 单文件上传 */
@RestController
public class FileUploadController {
    SimpleDateFormat sdf = new SimpleDateFormat("/yyyy/MM/dd/");

    @PostMapping("/upload")
    public String upload(MultipartFile file, HttpServletRequest request) {
        String s = sdf.format(new Date());
        String path = "D:\\fileUpload" + s;
        File folder = new File(path);
        if (!folder.exists()) {
            folder.mkdirs();
        }
        //旧文件名
        String oldName = file.getOriginalFilename();
        //新文件名
        String newName = UUID.randomUUID().toString() + oldName.substring(oldName.lastIndexOf("."));
        //上传文件
        try {
            file.transferTo(new File(folder,newName));
            String s1 = request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort() + s + newName;
            return s1;
        } catch (IOException e) {
            e.printStackTrace();
        }
        return "";
    }

}

相关文章