本篇文章主要介绍在Springboot中如何上传文件

引入依赖

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

上传页面

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

application.properties配置文件

#限制请求上传单个文件大小
spring.servlet.multipart.max-file-size=5KB
#限制请求上传总文件大小
spring.servlet.multipart.max-request-size=5KB
#spring.http.multipart.max-file-size=5KB  老版本
#spring.http.multipart.max-request-size= 5KB   老版本

Controller类

package com.example.springboot_uploadfile.controller;

import ch.qos.logback.core.util.FileUtil;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.FileOutputStream;

/**
 * @author XuJD
 * @create 2018-11-01 18:02
 **/
@Controller
public class IndexController {
    @RequestMapping("/index")
    public String index(){
        return "index";
    }

    @ResponseBody
    @RequestMapping("/upload")
    public String upload(@RequestParam("file")MultipartFile file, HttpServletRequest request){
        String fileName = file.getOriginalFilename();
        try {
            //文件上传到目标地址
            String filePath = "G:\\demo\\fileUpload\\";
            File targetFile = new File(filePath);
            if(!targetFile.exists()){
                targetFile.mkdirs();
            }
            FileOutputStream out = new FileOutputStream(filePath+fileName);
            out.write(file.getBytes());
            out.flush();
            out.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "上传成功";
    }
}

测试
一起学习Springboot(六):文件上传
一起学习Springboot(六):文件上传
上传一个超过5KB大小的文件试试,可以发现会报如下错误

一起学习Springboot(六):文件上传

示例代码下载-githubhttps://github.com/xujiangdong/SpringbootLearn

相关文章:

  • 2021-06-16
  • 2021-12-19
  • 2022-02-19
  • 2021-11-03
  • 2022-12-23
  • 2022-12-23
猜你喜欢
  • 2022-12-23
  • 2021-10-13
  • 2021-09-21
  • 2021-10-14
  • 2021-04-15
  • 2021-04-09
相关资源
相似解决方案