Spring MVC上传图片

确认数据库中维护头像的字段:

application.properties

spring.datasource.driver-class-name=com.mysql.jdbc.Driver
spring.datasource.url=jdbc:mysql://localhost:3306/store?serverTimezone=GMT%2B8&useSSL=false&characterEncoding=utf8&connectTimeout=3000
spring.datasource.username=root
spring.datasource.password=root

mybatis.mapper-locations=classpath:mapper/*.xml

前端的页面展示:

前端的HTML代码

<!--上传头像表单开始-->
<form class="form-horizontal" role="form"
      action="/user/chang_avatar"
      method="post"
      enctype="multipart/form-data"
      id="form-change-avatar">
    <div class="form-group">
        <label class="col-md-2 control-label">选择头像:</label>
        <div class="col-md-5">
            <img id="img-avatar" src="../images/index/user.jpg" class="img-responsive"/>
        </div>
        <div class="clearfix"></div>
        <div class="col-md-offset-2 col-md-4">
            <input type="file" name="file">
        </div>
    </div>
    <div class="form-group">
        <div class="col-sm-offset-2 col-sm-10">
            <input type="button" class="btn btn-primary" value="上传"
            id="btn-change-avatar"/>
        </div>
    </div>
</form>

前端的JS

$("#btn-change-avatar").click(function () {
    $.ajax({
        url: "/user/chang_avatar",
        type: "POST",
        data: new FormData($("#form-change-avatar")[0]),
        // 关闭数据处理
        processData: false,
        // 关闭默认提交数据的形式
        contentType: false,
        dataType: "json",
        success: function (json) {
            if (json.state == 200) {
                alert("修改成功");
                $("#img-avatar").attr("src", json.data)
            } else {
                alert("修改失败:" + json.msg);
            }
        },
        error: function (xhr) {
            alert("修改时产生了未知的错误异常:" + xhr.status);
        }
    });
});

Mapper.xml

<update id="updateAvatarByUid">
    update t_user
    set avatar=#{avatar},
        modified_user=#{modifiedUser},
        modified_time=#{modifiedTime}
    where uid = #{uid}
</update>

Mapper

@Mapper
public interface UserMapper {

    Integer updateAvatarByUid(User user);

}

Service

@Service
public class UserServiceImpl implements UserService {

    @Autowired
    UserMapper userMapper;

    @Override
    public Integer changeAvatar(User user) {

        User dbUser = userMapper.findByUid(user.getUid());
        if (dbUser == null || dbUser.getIsDelete().equals(1)) {
            throw new UsernameNotFoundException("用户不存在");

        } else {
            user.setModifiedUser(user.getModifiedUser());
            user.setModifiedTime(new Date());

            Integer rows = userMapper.updateAvatarByUid(user);
            if (rows != 1) {
                throw new UpdateException("更新时产生了未知异常");
            }
            return rows;
        }


    }

}

Controller

@RestController
@RequestMapping("/user")
public class UserController extends BaseController {

    private static final int AVATAR_MAX_SIZE = 10 * 1024 * 1024;

    public static final List<String> AVATAR_TYPE = new ArrayList<>();

    static {
        //jpeg包含了jpg
        AVATAR_TYPE.add("images/jpeg");
        AVATAR_TYPE.add("images/bmp");
        AVATAR_TYPE.add("images/bmp");
        AVATAR_TYPE.add("images/gif");
    }

    @PostMapping("/chang_avatar")
    public JsonResult<String> changeAvatar(HttpSession session, MultipartFile file) {
        if (file == null) {
            throw new FileEmptyException("文件为空");
        } else if (file.getSize() > AVATAR_MAX_SIZE) {
            throw new FileSizeException("文件大小过大");
        } else if (!AVATAR_TYPE.contains(file.getContentType())) {
            throw new FileTypeException("文件类型不匹配");
        } else {
            // 文件路径
            String path = session.getServletContext().getRealPath("upload");
            File dir = new File(path);
            if (!dir.exists()) {
                dir.mkdirs();
            }
            // 随机文件名
            String originalFilename = file.getOriginalFilename();
            int index = originalFilename.lastIndexOf('.');
            String suffix = originalFilename.substring(index); // 文件的后缀名
            String filename = UUID.randomUUID().toString().toUpperCase() + suffix;
            File dest = new File(dir, filename);
            try {
                // 文件的写入
                file.transferTo(dest);
            } catch (FileStateException e) {
                throw new FileStateException("文件状态异常,请先关闭文件");
            } catch (IOException e) {
                throw new FileUploadIOException("文件读写异常");
            }

            User user = new User();
            Integer uid = getUidFromSession(session);
            String username = getUsernameFromSession(session);
            user.setUid(uid);
            user.setUsername(username);
            user.setModifiedUser(username);

            String avatar = "/upload/" + filename;
            user.setAvatar(avatar);
            userService.changeAvatar(user);

            return new JsonResult<>(OK, "OK", avatar);
        }
    }

}

解决头像文件太大,配置application.properties文件:

spring.servlet.multipart.max-file-size=50MB
spring.servlet.multipart.max-request-size=50MB

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

蒋劲豪

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值