图片跟随表单一起上传
前端如果直接读图片的二进制数据在数据传输时会报错,所以先读取图片的字符串数据存到额外参数再传到后台进行转换可以比较简单的实现。
vue前端用elementUI上传组件**auto-upload=“false”**关闭自动上传
<el-upload class="avatar-uploader" action="#" :show-file-list="false" :on-change='changeUpload' :auto-upload="false" :before-upload="beforeAvatarUpload">
<img v-if="depart.imageUrl" :src="depart.imageUrl" class="avatar">
<i v-else class="el-icon-plus avatar-uploader-icon"></i>
</el-upload>
<script>
const defaultDepart = {
imageUrl: ''
},
methods: {
init (depart) {
if (this.depart.departImg) {
this.depart.imageUrl = 'data:image/jpeg;base64,' + this.depart.departImg
} else {
this.depart.imageUrl = ''
}
},
beforeAvatarUpload (file) {
const isJPG = file.type === 'image/jpeg'
const isLt2M = file.size / 1024 / 1024 < 2
if (!isJPG) {
this.$message.error('上传头像图片只能是 JPG 格式!')
}
if (!isLt2M) {
this.$message.error('上传头像图片大小不能超过 2MB!')
}
return isJPG && isLt2M
},
changeUpload: function (file, fileList) {
let reader = new FileReader()
reader.onload = async (e) => {
try {
this.depart.imageUrl = e.target.result
this.depart = deepCopy(this.depart || defaultDepart)
// let document = JSON.parse(e.target.result)
} catch (err) {
console.log(`load JSON document from file error: ${err.message}`)
this.showSnackbar(`Load JSON document from file error: ${err.message}`, 4000)
}
}
reader.readAsDataURL(file.raw)
}
}
</script>
<style>
.spacing {
margin-bottom: 22px !important;
}
.avatar-uploader
.el-upload {
border: 1px dashed
#d9d9d9;
border-radius: 6px;
cursor: pointer;
position: relative;
overflow: hidden;
}
.avatar-uploader
.el-upload:hover {
border-color: #409eff;
}
.avatar-uploader-icon {
font-size: 28px;
color: #8c939d;
width: 178px;
height: 178px;
line-height: 178px;
text-align: center;
}
.avatar {
width: 178px;
height: 178px;
display: block;
}
</style>
实体添加额外参数用于存放图片字符串
@Transient
@JsonInclude(JsonInclude.Include.NON_DEFAULT)
private String imageUrl;
后台直接用实体get然后转成byte存进类型为blob的字段
String image = ConvertUtil.getString(entity.getImageUrl());
entity.setDepartImg(base64ToByte(entity.getImageUrl()));
base64转byte函数
public byte[] base64ToByte(String image){
String header = "data:image/jpeg;base64,";
if (null != image && image.indexOf(header) == 0) {
image = image.substring(header.length());
byte[] decodedByte = Base64.decode(image.getBytes());
return decodedByte;
}
return null;
}