使用Springboot实现文件的上传

本文介绍了如何在Springboot应用中实现文件上传功能。首先,引入web依赖;然后,创建上传文件的HTML测试页面;接着,配置yml文件限制上传文件大小;最后,编写上传接口并实现将文件保存到本地。通过POST请求,可以成功上传文件。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

使用Spring boot上传文件

1、首先要导入依赖web

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

2、编写上传的测试页面

<h3>上传单个文件</h3>
    <form action="/upload" enctype="multipart/form-data" method="post">
        <input type="file" name="file" required><br>
        <input type="submit" value="上传单个文件">
    </form>

3、在yml文件中配置上传文件的大小

servlet:
    multipart:
      max-file-size: 100MB #单个文件上传最大值

4、编写接口

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 {

    @PostMapping("/upload")
    public Object upload(@RequestParam("file") MultipartFile file){
        return saveFile(file);
    }
    private Object saveFile(MultipartFile file){
        if (file.isEmpty()){
            return "未选择文件";
        }
        String filename = file.getOriginalFilename(); //获取上传文件原来的名称
        String filePath = "F:\\Work\\LuxaingJsp\\src\\main\\resources\\static\\video\\";
        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";
    }
}

上传文件必须是post请求方式

评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值