springboot接收postman上传的文件并保存在本地主机

1.写pom文件

导入web依赖即可

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

2.写yml

spring:
  servlet:
    multipart:
      enabled: true
# 上传文件总的最大值
      max-request-size: 10MB
# 单个文件的最大值
      max-file-size: 10MB


3.写controller

代码里的LOGGER和Result不是必需的

package com.example.yida_project.web;

import com.example.yida_project.pojo.User;
import com.example.yida_project.pojo.UserInformation;
import com.example.yida_project.service.UserInformationService;
import com.example.yida_project.service.UserService;
import com.example.yida_project.util.Result;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpSession;
import java.io.File;
import java.io.IOException;

@RestController
public class UserController {

    private static final Logger LOGGER = LoggerFactory.getLogger(UserController.class);
    @Autowired
    UserService userService;


    @PostMapping("/upload")
    public Object upload(@RequestParam("file") MultipartFile file) {
        if (file.isEmpty()) {
            return "上传失败,请选择文件";
        }

        String fileName = file.getOriginalFilename();
        String filePath = this.getClass().getResource("/").getPath();
        File dest = new File(filePath + fileName);
        try {
            file.transferTo(dest);
            LOGGER.info("上传成功");
            return Result.success("上传成功");
        } catch (IOException e) {
            LOGGER.error(e.toString(), e);
        }
        return Result.fail("上传失败");
    }

}

4.postman设置并文件上传

4.1 改header

此处主要注意Content-Type这个key,网上很多说法是不勾选这个,但是我不勾选后会报错500
在这里插入图片描述

4.2改body

参考如下,注意key需要选择file类型,并手动输入字符串,这个字符串和后端的@RequestParam(arg)中的arg同名
在这里插入图片描述

之后点击发送请求应该就可以返回上传成功的消息了。

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值