昨天受到启发想做一个头像上传的功能,但是转念一想似乎一个上传头像而已,没必要用form表单做同步刷新,请教了一下学长,他说让我用二进制的形式发送到后台,于是我百度了一天,在各种报错下终于还是做出来了

这里是html代码

<div class="pull-right hportrait" @mouseover="nupload">
    <input type="file" class="file" @change="selectImage" ref="file">
    <div style="margin-left: 10px;">{{upload}}</div>
    <input type="reset" value="取消" style="width: 45px;margin-top: 80px;font-size: 14px;" v-if="sub" @click="oupload" />
    <input type="submit" value="上传" style="width: 45px;margin-top: 80px;font-size: 14px;" v-if="sub" @click="oupload2" />
</div>

Vue中几个方法(属性我就不放上了,这个看着改就行了)

nupload(){
            this.upload = "更换头像"
            this.sub = true
        },
        oupload(){
            this.upload = ""
            this.sub = false
        },
        oupload2(){
            this.upload = ""
            this.sub = false
            this.$http.post('/api/setImg',{"image":this.image},{emulateJSON: true}).then(function(result){
                var x = result.bodyText;
                if(x=="yes"){
                    alert("上传成功")
                }else{
                    alert("上传失败")
                }
            })
        },
        selectImage(){
            var file = this.$refs.file.files[0]
            var reader = new FileReader();
            reader.readAsDataURL(file)
            reader.onload = ()=>{
                this.image = reader.result
            }
        }
    }

重点在于selectImage方法中最终赋予的image的值,就是我们所需要的

java部分代码,这里用的是ssm框架,这里我看到网上的部分代码收到了启发,用逗号,斜杠等符号分割了字符串,把后缀名和二进制码拿到手,然后指定了保存的路径(没有就创建),最后用输出流把图片输出。但是要注意这里图片的名字并不重要了,直接用的是System.currentTimeMillis()方法生成的时间毫秒数,把它放到数据库里以后想要再传过来用url拿就可以了。

@ResponseBody
	@RequestMapping("setImg")
	public String setImg(@RequestParam String image) throws IOException{
		int index = image.indexOf(",");
		int index2 = image.indexOf("/");
		int index3 = image.indexOf(";");
		String type = image.substring(index2+1,index3);
        image = image.substring(index+1);
        /**用base64解码,decode方法将其转成二进制编码*/
        Decoder decoder = Base64.getDecoder();
        byte[] bytes = decoder.decode(image.replace("\r\n", ""));
        long time = System.currentTimeMillis();
        /**指定保存的路径*/
        File path = new File("E:/apped/");
        if(!path .exists()) {
        	path.mkdirs();
        }
        path = new File("E:/apped/"+time+"."+type);
        FileOutputStream outputStream = new FileOutputStream(path);
        outputStream.write(bytes);
        outputStream.close();
	    return "yes";
	}

当然,很多部分没有完善,异常都是直接抛出去的,如果有想法可以自己改下加强其健壮性

Logo

魔乐社区(Modelers.cn) 是一个中立、公益的人工智能社区,提供人工智能工具、模型、数据的托管、展示与应用协同服务,为人工智能开发及爱好者搭建开放的学习交流平台。社区通过理事会方式运作,由全产业链共同建设、共同运营、共同享有,推动国产AI生态繁荣发展。

更多推荐