基于jQuery的文件上传 #yyds干货盘点#
页面<img src="${user.avatar}" alt="用户头像" id="userAvatar" style="width:120px;height:120px;">
<form id="userAvatarForm" enctype="multipart/form-data">
<input type="hidden" id="id" value="${user.id}">
修改头像:<input type="file" name="avatar" id="img">
<input type="button" value="提交" >
</form>
.......
<script type="text/javascript">
function updateAvatar() {
let formData = new FormData($('#userAvatarForm'));
formData.append("avatar", $("#img").files);
formData.append("id", $("#id").val());
let uploading = false;
if (uploading) {
alert("文件正在上传中,请稍候!");
return false;
}
$.ajax({
url: '/projshow/user/updateAvatar', /*接口域名地址*/
type: 'POST',
data: formData,
contentType: false,
processData: false,
dataType: "json",
beforeSend: function () {
uploading = true;
console.log(uploading);
},
success: function (res) {
uploading = false;
console.log(res);
if (res.code == 200){
$("#userAvatar").attr('src',res.data);
}
}
})
}注意:外层的form表单不能省略,form的enctype值必须为multipart/form-data
后台控制器代码
@Slf4j
@Controller
@RequestMapping("/user")
public class UserController {
@ResponseBody
@PostMapping("/updateAvatar")
public Result updateAvatar(@RequestParam("avatar") MultipartFile multipartFile,
Long id ) {
String avatarUrl = null;
try {
avatarUrl = AliOSSUtil.upload(multipartFile);
} catch (IOException e) {
throw new GlobalException(408,"图片上传到图片服务器出错");
}
User user = User.builder()
.id(id)
.avatar(avatarUrl)
.build();
userService.updateByPrimaryKeySelective(user);
return Result.success(avatarUrl);
}
}
效果
</div>
<div id="asideoffset"></div>
https://blog.51cto.com/lianghecai/4629445
页:
[1]