springboot 实现文件上传

springboot 项目实现文件上传

application.yaml 配置文件内容
spring:
  servlet:
    multipart:
      max-request-size: 5GB  # 上传文件总的最大值 默认10MB
      max-file-size: 1GB #单个文件最大值 默认10MB

# 文件保存的目录
upload: D:\Users\zdz\IdeaProjects\fileupload\upload\
controller代码:
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;

    @RestController
    public class UpLoadController {
        @Value("${upload}")
        String filePath;

        @PostMapping("/upload")
        public Object upload(@RequestParam("file") MultipartFile file){
            return saveFile(file);
        }

        @PostMapping("/multiUpload")
        public Object multiUpload(@RequestParam("file")MultipartFile[] files){
            System.out.println("文件的个数:"+files.length);
            for (MultipartFile f : files){
                saveFile(f);
            }
            return "ok";
        }

        /**
         *  文件上传,核心逻辑!
         */
        private Object saveFile(MultipartFile file){
            if (file.isEmpty()){
                return "未选择文件";
            }
            // 获取文件上传时的名字
            String filename = file.getOriginalFilename(); 

            File temp = new File(filePath);
            if (!temp.exists()){
                temp.mkdirs();
            }

            File localFile = new File(filePath+filename);
            try {
            	// 将文件保存到本地!
                file.transferTo(localFile); 
                System.out.println(file.getOriginalFilename()+" 上传成功");
            }catch ( IOException e){
                e.printStackTrace();
                return "上传失败";
            }

            return "ok";
        }
    }
前端代码
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>上传文件</title>
</head>
<body>
<center>
    <h3>上传文件</h3>
    <form action="/upload" enctype="multipart/form-data" method="post">
        <input type="file" name="file" required><br>
        <input type="submit" value="上传单个文件">
    </form>
</center>
</body>
</html>

  • 2
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值