springboot 上传文件

在Spring Boot中,可以使用@RequestParam注解来接收文件。

在你的控制器方法中,使用@RequestParam注解来声明一个MultipartFile类型的参数来接收上传的文件

MultipartFile是spring类型,代表HTML中form data方式上传的文件,包含二进制数据+文件名称。在文件上传这方面能帮助我们快速简洁实现。

@RequestParam注解的required属性默认为true,如果请求中不包含名为file的文件,将会抛出异常。如果想要文件是可选的,可以将required属性设置为false

我们新增一个 UploadController.java文件

package shop.controller;

import org.springframework.web.bind.annotation.RequestMapping;
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.util.HashMap;
import java.util.Map;

@RestController
@RequestMapping("api")
public class UploadController {
    private String uploadFilePath = "D:\\2023\\toby.com\\file\\upload";

    @RequestMapping("upload")
    public Map<String,Object> upload(@RequestParam("files") MultipartFile files[]){
        Map<String,Object> res = new HashMap<>();

        for(int i=0;i<files.length;i++){
            String fileName = files[i].getOriginalFilename();  // 文件名
            File dest = new File(uploadFilePath +'/'+ fileName);
            if (!dest.getParentFile().exists()) {
                dest.getParentFile().mkdirs();
            }
            try{
                files[i].transferTo(dest);
            }catch (Exception e){
                System.out.println(e.toString());
                res.put("code",1);
                res.put("message","upload error");
                return res;
            }

        }

        res.put("code",0);
        return res;
    }
}

编译运行项目 使用postman发生上传文件请求

文件上传成功我们可以在项目中看到 新上传上来的文件

获取源代码

链接:https://pan.baidu.com/s/1nOHKaWfa2yLzP8SYq1kSgQ

提取码:vth8

加入我们一起学校

 

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值