一、前端设置前端是vue + element-ui 采用el-upload组件(借鉴官方)上传图片:
<el-upload ref="upload" class="avatar-uploader" action="/setimg" :http-request="picupload" :show-file-list="false" :auto-upload="false" :on-success="handleavatarsuccess" :before-upload="beforeavatarupload"> <img v-if="$hosturl+imageurl" :src="$hosturl+imageurl" class="avatar"> <i v-else class="el-icon-plus avatar-uploader-icon"></i> </el-upload><el-button type="primary" @click="submitupload">修改</el-button>
action在这里可以随便设置,因为在后面有 :http-request 去自己设置请求,注意由于是自己写请求需要 :auto-upload=“false” ,并且由于是前后端连接要解决跨域问题,所以在 $hosturl+imageurl 定义了一个全局变量:
//在main.js中 vue.prototype.$hosturl='http://localhost:8082'
在methods中:
methods:{//这里是官方的方法不变 handleavatarsuccess(res, file){ this.imageurl = url.createobjecturl(file.raw); }, 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; },//这里是自定义发送请求 picupload(f){ let params = new formdata() //注意在这里一个坑f.file params.append("file",f.file); this.$axios({ method:'post', //这里的id是我要改变用户的id值 url:'/setimg/'+this.userform.id, data:params, headers:{ 'content-type':'multipart/form-data' } }).then(res=>{ //这里是接受修改完用户头像后的json数据 this.$store.state.menu.currentuserinfo=res.data.data.backuser //这里返回的是头像的url this.imageurl = res.data.data.backuser.avatar }) }, //触发请求 submitupload(){ this.$refs.upload.submit(); }}
在上面代码中有一个坑 f.file ,我看了许多博客,发现有些博客只有 f 没有 .file 导致出现401、505错误。
二、后端代码1.建立数据库
这里头像avatar是保存的上传图片的部分url
2.实体类、mapper实体类:
采用mybatis plus
@datapublic class sysuser extends baseentity{//这里的baseentity是id,statu,created,updated数据 private static final long serialversionuid = 1l; @notblank(message = "用户名不能为空") private string username;// @tablefield(exist = false) private string password; @notblank(message = "用户名称不能为空") private string name; //头像 private string avatar; @notblank(message = "邮箱不能为空") @email(message = "邮箱格式不正确") private string email; private string tel; private string address; @tablefield("plevel") private integer plevel; private localdatetime lastlogin;}
@mapper@tablename("sys_user")public interface sysusermapper extends basemapper<sysuser> {}
3.接受请求,回传数据 @value("${file.upload-path}") private string pictureurl; @postmapping("/setimg/{id}") public result setimg(@pathvariable("id") long id, @requestbody multipartfile file){ string filename = file.getoriginalfilename(); file savefile = new file(pictureurl); //拼接url,采用随机数,保证每个图片的url不同 uuid uuid = uuid.randomuuid(); //重新拼接文件名,避免文件名重名 int index = filename.indexof("."); string newfilename ="/avatar/"+filename.replace(".","")+uuid+filename.substring(index); //存入数据库,这里可以加if判断 sysuser user = new sysuser(); user.setid(id); user.setavatar(newfilename); sysusermapper.updatebyid(user); try { //将文件保存指定目录 file.transferto(new file(pictureurl + newfilename)); } catch (exception e) { e.printstacktrace(); } system.out.println("保存成功"); sysuser ret_user = sysusermapper.selectbyid(user.getid()); ret_user.setpassword(""); return result.succ(maputil.builder() .put("backuser",ret_user) .map()); }
yml文件中图片的保存地址:
file: upload-path: d:\study\myadmin\scr
三、显示图片1.后端配置实现前端vue :scr 更具url显示头像图片,则必须设置webmvc中的静态资源配置
建立webconfig类
@configurationpublic class webconfig implements webmvcconfigurer{ private string filepath = "d:/study/myadmin/scr/avatar/"; @override public void addresourcehandlers(resourcehandlerregistry registry) { registry.addresourcehandler("/avatar/**").addresourcelocations("file:"+filepath); system.out.println("静态资源获取"); }}
这样就可是显示头像图片了
2.前端配置注意跨域问题以及前面的全局地址变量
vue.config.js文件(若没有则在scr同级目录下创建):
module.exports = { devserver: { // 端口号 open: true, host: 'localhost', port: 8080, https: false, hotonly: false, // 配置不同的后台api地址 proxy: { '/api': { //后端端口号 target: 'http://localhost:8082', ws: true, changorigin: true, pathrewrite: { '^/api': '' } } }, before: app => {} }}
main.js:
axios.defaults.baseurl = '/api'
以上就是怎么用springboot+vue实现图片上传至数据库并显示的详细内容。
