springboot整合swagger测试上传文件失效
说明:
正常我们使用swagger,正常接口crud操作都是可以的,但是特殊的请求,比如header里面加token,上传文件等可能不支持,我们就需要使用postman,当然了,能使用swagger我们还是使用swagger,因为swagger方便
出现失效情况情景再现
@Controller
@Api(tags = "base64转图片")
@RequestMapping("Base64Controller")
public class Base64Controller {
@PostMapping("/testbase64")//get请求
// @ResponseBody
@ApiOperation(value = "上传图片并回显图片", notes = "", httpMethod = "")
public String uploadAndShow(HttpServletRequest request, MultipartFile fileupload, Model model) throws IOException {
byte[] fileByte = fileupload.getBytes();
if(fileByte.length==0){
throw new RuntimeException("文件为空,请重新选择文件");
}
BASE64Encoder encoder = new BASE64Encoder();
// File file = new File("G:\\图书馆.jpg");
// byte[] fileByte = Files.readAllBytes(file.toPath());
String baseStr = encoder.encode(fileByte);
String imgStr = "data:image/jpeg;base64," + baseStr;
model.addAttribute("base", imgStr);
return "base";
}
}
解决方法
在MultipartFile加上@RequestPart注解即可
正确方式
@Controller
@Api(tags = "base64转图片")
@RequestMapping("Base64Controller")
public class Base64Controller {
@PostMapping("/testbase64")//get请求
// @ResponseBody
@ApiOperation(value = "上传图片并回显图片", notes = "", httpMethod = "")
public String uploadAndShow(HttpServletRequest request, @RequestPart MultipartFile fileupload, Model model) throws IOException {
byte[] fileByte = fileupload.getBytes();
if(fileByte.length==0){
throw new RuntimeException("文件为空,请重新选择文件");
}
BASE64Encoder encoder = new BASE64Encoder();
// File file = new File("G:\\图书馆.jpg");
// byte[] fileByte = Files.readAllBytes(file.toPath());
String baseStr = encoder.encode(fileByte);
String imgStr = "data:image/jpeg;base64," + baseStr;
model.addAttribute("base", imgStr);
return "base";
}
@RequestParam和@RequestPart的区别
参考网址:
https://blog.csdn.net/u012894692/article/details/115875674?ops_request_misc=%257B%2522request%255Fid%2522%253A%2522162195196216780271545090%2522%252C%2522scm%2522%253A%252220140713.130102334…%2522%257D&request_id=162195196216780271545090&biz_id=0&utm_medium=distribute.pc_search_result.none-task-blog-2allbaidu_landing_v2~default-1-115875674.first_rank_v2_pc_rank_v29&utm_term=%40RequestPart+%E4%BD%9C%E7%94%A8&spm=1018.2226.3001.4187
总结
term=%40RequestPart+%E4%BD%9C%E7%94%A8&spm=1018.2226.3001.4187
总结
当请求头中指定Content-Type:multipart/form-data时,@RequestPart注解可以用对象来接收