MissingServletRequestPartException: Required request part ‘file‘ is not present]

Error:

2020-10-20 19:09:32.298  WARN 5696 --- [nio-8080-exec-6] .w.s.m.s.DefaultHandlerExceptionResolver : Resolved [org.springframework.web.multipart.support.MissingServletRequestPartException: Required request part 'file' is not present]
2020-10-20 19:19:37.187  WARN 5696 --- [nio-8080-exec-1] .w.s.m.s.DefaultHandlerExceptionResolver : Resolved [org.springframework.web.multipart.support.MissingServletRequestPartException: Required request part 'file' is not present] 

Solution analysis:
In the userController file @RequestParam("avatar"), [avatar] is written as [file] and
modified:

@PostMapping("change_avatar")
	public JsonResult<String> changeAvatar(
			@RequestParam("avatar") MultipartFile file,
			HttpSession session) {
		// 判断上传的文件是否为空
		if (file.isEmpty()) {
			// 是:抛出异常

Attached:

  1. The problem I encountered was caused by the inconsistency between the field value in the annotation and the name field value in the input tag.
<div class="cen1">
	<input type="file" name="avatar" class="file">
</div>

2. Master ignores! Note:
In jQuery:
[.] in [$(".btn-change-avatar")] takes the value of the class attribute

[#] value id attribute in [$("#btn-change-avatar")]

$(".btn-change-avatar").click(function(){
    
    
			$.ajax({
    
    
				"url":"/users/change_avatar",
				"data":new FormData($(".form-change-avatar")[0]),
				"processData":false,
				"contentType":false,
				"type":"POST",
				"dataType":"json",
				"success":function(json) {
    
    
					console.warn("正在执行:"+json);
					if (json.state == 2000) {
    
    
						alert("修改成功!");
						console.log(json.data);
						// 显示新头像
						$(".img-avatar").attr("src",json.data);
						// 把新头像路径更新到cookie中
						$.cookie("avatar", json.data, {
    
    "expires": 7});
					}else{
    
    
						alert("修改失败!" + json.message + "!");
					}
				},
				"error":function(xhr, textStatus, errorThrown) {
    
    
					alert("您的登录信息已经过期,请重新登录!\n\n响应码:" + xhr.status);
				}
			});
			return false;
		});
		```


源码:
	Git clone https://gitee.com/gzllkm/course.git

Guess you like

Origin blog.csdn.net/weixin_44182157/article/details/109187321