2021-05-11 15:06

Vue前端使用axios上传base64图片,SpringBoot后端解析并保存图片

王姐姐

WEB前端

(1836)

(0)

收藏

小文件可以使用base64上传,大文件不建议使用base64,速度慢。

1 前端实现图片预览和axios上传

   <div id="app">
        <input type="file" ref="picFile"/>
        <img :src="imgData" style="max-width: 100px"/>
        <button @click="upload">上传</button>
    </div>
	<script>
 var app = new Vue({
     el:"#app",
     data:{
         imgData:''
     },
     methods:{
         upload:function(){
             var file = this.$refs.picFile.files[0];
           
             var fileReader = new FileReader();
             //文件打开后的回调函数
             fileReader.onload= e=>{               
                 var base64 = e.target.result;
                 //图片预览
                 this.imgData=base64;                
                 console.log(base64);                 
                 //上传图片
                 axios.post(basePath+"/wanmaitupload",base64).param
                 .then(res=>{
                     console.log("上传成功");
                 });
             };
             //打开文件
             fileReader.readAsDataURL(file);
             
         }
     }
 });
</script>

2 后端解析base64数据并保持文件

一定注意后端需要URL解码,并且把加号+自动变为空格了,需要再替换回去

    @PostMapping("/wanmaitupload")
    public Result uploadBase64(@RequestBody  String base64) throws IOException {
        base64 = URLDecoder.decode(base64, "UTF-8");
        System.out.println(base64);
        //Illegal base64 character 20 base64 编码中使用了加号(+),而 + 在 URL 传递时会被当成空格,因此造成了base64字符串被更改,在服务器端解码后就会出错
        base64=base64.replaceAll(" ","+");
        System.out.println(base64);
        if(!base64.startsWith("data:image/"))
        {
            return Result.error("只能上传图片");
        }
        String regex = "data:image/(\\w+);base64,(.*)";
        Pattern pattern = Pattern.compile(regex);
        Matcher matcher = pattern.matcher(base64);
        String ext=null;
        if(matcher.find()){
            ext = matcher.group(1);
            base64=matcher.group(2);
        }
        else {
            return Result.error("只能上传图片");
        }
        //java.util.Base64
        byte[] byteData = Base64.getDecoder().decode(base64);
        //org.springframework.util.Base64Utils;
        //byte[] byteData = Base64Utils.decodeFromString(base64);
        //图片保存路径
        String path = ResourceUtils.getURL("classpath:").getPath();
        path += "/static/uploadImages";
        String filename = UUID.randomUUID().toString().replaceAll("-", "") + "." + ext;
        File file = new File(path,filename);
        //org.apache.commons.io.FileUtils
        FileUtils.writeByteArrayToFile(file,byteData);

        return Result.success("上传成功"+filename);
    }


0条评论

点击登录参与评论