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同名
之后点击发送请求应该就可以返回上传成功的消息了。