效果预览
SSM头像上传
看看这要求: 目前仅支持腾讯视频、优酷视频、哔哩哔哩视频、已上传视频
真的烦人,还需要上传到腾讯视频,才行,哎!
前端布局(js)
<button id="updateImg">更改头像</button>
<input type="file" id="file" style="display: none">
<div class="img">
<img src="${pageScope.basePath}user/img?id=1" style="width: 50px;height:50px;border-radius: 25px;display: inline-block;background-position: center center;" alt="">
</div>
$(function () {
//更改头像
$('#updateImg').click(function () {
var $file=$('#file');
//触发文件按钮的点击事件
$file.click();
//选择文件后,获取上传的图片
$file.change(function () {
//获取上传的图片
var file=$file[0].files[0];
//检验是否为图像
if(!/image\/\w+/.test(file.type)){
alert("抱歉,只支持图片类型哦!");
return false;
}
if(file.size/1024>65){
alert('文件太大,必须小于65k!');
return false;
}
var reader = new FileReader();
//将文件以Data URL形式读入页面
reader.readAsDataURL(file);
reader.onload=function () {
//将img中的图像更改成更改后的图像,并上传
$('.img img').attr('src',this.result);
};
var id=1;//获取id,这里假设为1
//利用formData传送数据
var data=new FormData();
data.append("id",id);
data.append("file",file);
$.ajax({
url:"${pageScope.basePath}user/uploadImg",
data:data,
//上传文件无需缓存
cache: false,
contentType:false, //- 必须false才会自动加上正确的Content-Type
processData: false, //- 必须false才会避开jQuery对 formdata 的默认处理,XMLHttpRequest会对 formdata 进行正确的处理
type:'post',
success:function (result) {
if(result.code!==200){
//上传成功
}else{
alert(result.extend.error);
//取消更改,将数据库原来的图像设置
$('.img').empty();
$('.img').append($(" <img src=\"${pageScope.basePath}user/img?id="+id+"\" style=\"width: 50px;height:50px;border-radius: 25px;display: inline-block;background-position: center center;\" alt=\"\">"));
}
}
});
});
});
});
后端实现
1.mysql BLOB类型与JAVA 转换
BLOB=>byte[]
MySQL BLOB类型 MySQL中,BLOB是一个二进制大型对象,是一个可以存储大量数据的容器,它能容纳不同大小的数据。
1.2 user类:
package com.cy.pojo;
import com.baomidou.mybatisplus.annotation.TableName;
/**
* @author stardream Email:stardream0000@163.com
* @Description
* @ 2021/9/2 18:42
*/
@TableName("user")
public class User {
private Long id;
private String userName;
private String passWord;
private byte [] img;
private Integer role;
public User(){}
public User(Long id, String userName, String passWord, byte[] img, Integer role) {
this.id = id;
this.userName = userName;
this.passWord = passWord;
this.img = img;
this.role = role;
}
public User(Long id, String userName, String passWord) {
this.id = id;
this.userName = userName;
this.passWord = passWord;
}
public Long getId() {
return id;
}
public String getUserName() {
return userName;
}
public String getPassWord() {
return passWord;
}
public byte[] getImg() {
return img;
}
public Integer getRole() {
return role;
}
public void setId(Long id) {
this.id = id;
}
public void setUserName(String userName) {
this.userName = userName;
}
public void setPassWord(String passWord) {
this.passWord = passWord;
}
public void setImg(byte[] img) {
this.img = img;
}
public void setRole(Integer role) {
this.role = role;
}
@Override
public String toString() {
return "User{" +
"id=" + id +
", userName='" + userName + '\'' +
", passWord='" + passWord + '\'' +
", img=" + img +
", role=" + role +
'}';
}
}
1.3 userMapper
public interface UserMapper extends BaseMapper<User> {
User getOne(Long id);
List<User> getList();
List<User> getListByCons(@Param("id") Long id, @Param("userName") String userName, @Param("role") Integer role);
}
1.4 mpper.xml
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.cy.mapper.UserMapper">
<!-- 通用查询映射结果 -->
<resultMap id="BaseResultMap" type="com.cy.pojo.User">
<id column="id" property="id" />
<result column="user_name" property="userName"/>
<result column="pass_word" property="passWord"/>
<!-- 下面必须配置handler 否则获取不到-->
<result column="img" property="img" javaType="byte[]" jdbcType="BLOB" typeHandler="org.apache.ibatis.type.BlobTypeHandler"/>
<result column="role" property="role"/>
</resultMap>
<select id="getOne" resultMap="BaseResultMap">
select * from user where id=#{id}
</select>
<select id="getList" resultMap="BaseResultMap">
select * from user
</select>
<select id="getListByCons" resultMap="BaseResultMap">
select * from user
<where>
<if test="id!=null">
id=#{id}
</if>
<if test="userName!=null">
and user_name=#{userName}
</if>
<if test="role!=null">
and role=#{role}
</if>
</where>
</select>
</mapper>
1.5 userService
@Service
public class UserServiceImp implements UserService {
@Autowired
UserMapper userMapper;
/*
* @Description //TODO 只需传入id和img
* @Date
* @Param
* @return
**/
@Override
public Integer setHeadImg(User user) {
return userMapper.updateById(user);
}
@Override
public User getUser(Long id) {
return userMapper.getOne(id);
}
}
保存到数据库
controller 需配置文件解析
mvc中:
在这里插入代码片
<!--文件解析器-->
<bean id="multipartResolver"
class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
<property name="defaultEncoding" value="UTF-8"/>
<property name="maxUploadSize" value="1024000"/> //最大接收大小
/*
* @Description //TODO 上传图片,保存到数据库 也可更改
* @Date
* @Param
* @return
**/
@RequestMapping(value = "/uploadImg")
@ResponseBody
public Msg uploadImg(@RequestParam(value = "file",required = false)MultipartFile img,
@RequestParam(value = "id") Integer id) throws IOException, SQLException {
if(img!=null){
if(Math.floor((double)img.getSize()/1024)>65.0){
return Msg.fail().add("error","文件太大!");
}
InputStream inputStream = img.getInputStream();
User user=new User();
user.setId(Long.valueOf(id));
byte[] bytes = FileCopyUtils.copyToByteArray(inputStream);
user.setImg(bytes);
Integer i = userService.setHeadImg(user);
if (i>0){
return Msg.success();
}else{
return Msg.fail().add("error","上传失败!");
}
}else{
return Msg.fail().add("error","未上传图片!");
}
}
注;Msg是我自定义的信息返回类
传到前端页面
/*
* @Description //TODO 设置图片,将数据库中的图片传给前端
* @Date
* @Param
* @return 返回一张图片
**/
@RequestMapping("/img")
public void setHeadImg(@RequestParam(value = "id") Integer id, HttpServletResponse resp) {
User user = userService.getUser(Long.valueOf(id));
byte[] bytes = user.getImg();
OutputStream outputStream = null;
try {
outputStream=resp.getOutputStream();
outputStream.write(bytes);
outputStream.flush();
}catch (Exception e){
e.printStackTrace();
}finally {
try {
outputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}