vue+springboot实现头像上传和展示

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/QCIWYY/article/details/81868198

功能描述:上传头像,以及更换头像,具体实施步骤如下:

1.页面代码

<div class="set-form">
          <div class="set-pic-upload">
            <h3 class="set-label">选择本地照片</h3>
            <div class="set-ovhide">
            <el-upload class="upload-demo" action="user/saveImage" ref="upload" :auto-upload='false' :limit=limitNum
            :on-exceed="handleExceed" :on-change='changeUpload' accept="image/jpeg,image/gif,image/png">
              <div class="btn-line">
                <svg class="icon" aria-hidden="true">
                  <use xlink:href="#icon-upload"></use>
                </svg>
                <span>上传文件</span> 
              </div>
              <p class="cg9 mt10">不超过2M的gif、jpg、png图片</p>
              </el-upload>
            </div>
          </div>
          <div class="set-pic-dib">
            <h3 class="set-label">照片预览</h3>
            <div class="set-ovhide">
               <div class="picture-view">
                <div class="pic-v-box" id="img">
                  <!-- 上传图片放于此处 -->
                  <img :src="src" style="width: 334px;height:335px;" alt="">
                </div>
                <svg class="icon" aria-hidden="true">
                    <use xlink:href="#icon-img"></use>
                </svg>
              </div>
            </div>
          </div>
          <div class="set-pic-dib tc">
            <div class="set-pic-view"><img :src="src" style="width: 74px;height: 74px;margin-bottom:12px;border-radius: 50%;" alt=""></div>
            <p>头像预览</p>
          </div>
          <div class="set-btn-box">
	        <button class="btn-line btn-bo" v-on:click="cancel()">取&nbsp;消</button>
	        <button class="btn-line btn-bo" v-on:click="onclick()">保&nbsp;存</button>
          </div>
        </div>

2.js代码

var dataFuc = function dataFuc() {
			return {
				visible : false,
				loading : false,
				menuStyle:{
					isUserInfo:false,
					isImageSetting:true,
					isActivendicator:false,
				},
				src: '',
				limitNum: 1,
				fileName: '',
	            param:'',//表单要提交的参数
			}
		};
		
		var app = new Vue({
			el : '#app',
			data : dataFuc,
			methods : {
				changeUpload: changeUpload,
				handleExceed: handleExceed,
				onclick: onclick,
			},
		})
		
		function onclick(){
			var fileName = this.fileName;
			var reader = new FileReader();
		    reader.readAsDataURL(this.param.raw);
		    reader.onload = function(e){ 
	        var data = this.result; // 这个就是base64编码了
	        $.ajax({
				data : {image: data,fileName: fileName},
				type : "POST",
				url : contextRoot + 'user/saveImage',
				async : false,
				success : function(result) {
					if (result.code == 200) {
						console.log(result);
						showMsg("图片上传成功");
					}else {
						app.$message.error(result.msg)
					}
				}
			});
	        /* 此处停留1秒刷新页面 */
			setTimeout(function(){
				location.reload();
				},1000)
	      }
		}
		
		function cancel(){
			location. reload();
		}
		
		function changeUpload (file, fileList){
			console.log(file);
		      // 判断图片大小
		      if (fileList[0].size < 2200000) {
		        // 判断图片格式是否为jpg,png,jepg,gif
		        var fileName=fileList[0].name;
		        var url = fileList[0].url;
		        var suffix = fileName.substring(fileName.lastIndexOf(".")+1).toUpperCase()
		        if (suffix=="JPG"||suffix=="JPEG"||suffix=="PNG"||suffix=="GIF") {
		        	this.src=url;
		        	this.fileName=fileName;
		        	this.param=file;
		        } else {
		          this.$message.error('文件类型不正确,请重新上传!')
		        }
		      } else {
		        this.$message.error('图片大小超过2M,请重新上传')
		      }
		}
		
		// 文件超出个数限制时的钩子
		function handleExceed(file, fileList){
			this.$notify.warning({
		        title: '警告',
		        message: '只能选择一个文件!'
		      });
		}
		
		function showMsg(msg){
		   	app.$message({
		           showClose: true,
		           message: msg,
		           type: 'success',
		           duration: 3000
		         });
		   }

3.java后台代码,

①上传图片,将base64位的图片信息解析出来之后,存入数据库中既是imagePath

    
	@ResponseBody
	@PostMapping(value = "/saveImage")
	public BaseResponse<MyFavorite> saveImage(String image,String fileName,HttpServletRequest request){
		BaseResponse<MyFavorite> result = new BaseResponse<MyFavorite>();
		try {
		//输出base64 数据,截取","之后的值进行转换
        String str = image.substring(image.indexOf(",")+1);
        //System.currentTimeMillis()意思是获取当前系统的时间戳给图片命名
        //实例化Base64转换类  调用里面的GenerateImage方法(把base64数据转为图片)
        //第一个参数base64转图片的必须的base64数据,第二个是转换后生成的图片存放路径
        String imagePath = "E:/images/"+System.currentTimeMillis()+".png";
        GenerateImage(str, imagePath);
        //数据库存入绝对路径下的图片路径及名称(上传图片即是修改操作)
        String loginUser = SessionHelper.GetLoginUserCode();
		User user = userRepository.getByName(loginUser);
		user.setImagePath(imagePath);
		//更新用户头像地址
		userRepository.updateImagePath(user);
		result.code = 200;
		} catch (Exception e) {
			e.printStackTrace();
			result.code = 500;
			result.setMsg("服务器错误");
		}
		return result;
	}
	
	//base64字符串转化成图片  
    public static boolean GenerateImage(String imgStr,String imageName){
        //对字节数组字符串进行Base64解码并生成图片  
        if (imgStr == null) //图像数据为空  
            return false;  
        try{     
            //Base64解码  
        	byte[] b = Base64.decodeBase64(imgStr.replace("data:image/png;base64,",""));
        	imgStr = imgStr.replace("base64,","");
            for(int i=0;i<b.length;++i) {  
                if(b[i]<0){  
                //调整异常数据  
                    b[i]+=256;  
                }  
            }  
            //生成jpeg图片  
            String imgFilePath = imageName;//新生成的图片  
            OutputStream out = new FileOutputStream(imgFilePath);      
            out.write(b);  
            out.flush();  
            out.close();  
            return true;  
        } catch (Exception e) {   
            return false;  
        }  
    } 

②前端获取图片并展示,将路径放至需要展示图片地方即可;

@RequestMapping(value = "/showImg")
    @ResponseBody
    public void showImg( HttpServletRequest request,HttpServletResponse response) {
     String loginUser = SessionHelper.GetLoginUserCode();
	 User user = userRepository.getByName(loginUser);
	 //查询当前登录用户图片地址
	 String pathName = userRepository.getImagePath(user.getUserCode());
     File imgFile = new File(pathName);
     FileInputStream fin = null;
     OutputStream output=null;
     try {
      output = response.getOutputStream();
      fin = new FileInputStream(imgFile);
      byte[] arr = new byte[1024*10];
      int n;
      while((n=fin.read(arr))!= -1){
       output.write(arr, 0, n);
      }
      output.flush();
      output.close();
     } catch (IOException e) {
      e.printStackTrace();
     }

至此头像上传和展示的所有代码完成;可直接使用。

参考博客:前端:https://blog.csdn.net/guaiguaiknl/article/details/53607483

                  后台:https://blog.csdn.net/qq_36410795/article/details/72652027?locationNum=8&fps=1

猜你喜欢

转载自blog.csdn.net/QCIWYY/article/details/81868198