jQuery 文件上传

发布时间:2022-06-29 发布网站:脚本宝典
脚本宝典收集整理的这篇文章主要介绍了jQuery 文件上传脚本宝典觉得挺不错的,现在分享给大家,也给大家做个参考。

页面

<img src&#61;"${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}">
    修改头像F1a;<input type="file" name="avatar" id="img">
    <input type="button" value="提交" onclick="updateAvatar()">
</form>

.......

<script type="text/javascript">

    function updateAvatar() {
        let formData = new FormData($('#userAvatarForm')[0]);
        formData.append("avatar", $("#img")[0].files[0]);
        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);
    }

}

效果

jQuery 文件上传

脚本宝典总结

以上是脚本宝典为你收集整理的jQuery 文件上传全部内容,希望文章能够帮你解决jQuery 文件上传所遇到的问题。

如果觉得脚本宝典网站内容还不错,欢迎将脚本宝典推荐好友。

本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。