解决一切文件上传问题(保姆级) 前后端对接解决方案

前端设置一个文件上传按钮给其绑定一个内容改变事件@change
    example: 
        <input @change="fileFn" type="file" id="imgFile">  //示例用的vue,其他js也一样绑定方法不同而已
        在js中获取其上传的文件则是
        fileFn(ev) {
            if (ev.target.files[0]) { // ev.target.files 上传文件的集合,选择第一个做滤空判断
                let file = ev.target.files[0];
                // 将file文件转为base64  file为所读文件  res为转换后的base64编码的文件 使用回调函数将值传递出去
                // _this.file 要传递给后台的文件
                Common.toBase64(file, function (res) { //Common 自定义工具类,文章末尾有
                _this.file.data = res; //将base64的值赋予出去
                _this.file.fileName = file.name; // 将文件名赋值出去
                })
            }
        代码执行到此获取上传文件的代码就结束了后台我们直接正常提交即可,后台用字符串的方式接收数据即可
后台使用字符串类型接收
//將base64的文件类型自定义转换成byte数组或file文件  这里提供2个工具类方法 详情请看 https://blog.csdn.net/qq_35971258/article/details/80593500



工具类代码
/**
     *
     * @param path
     * @return String
     * @description 将文件转base64字符串
     * @date 2018年3月20日
     * @author changyl
     * File转成编码成BASE64
     */
    public static  String fileToBase64(String path) {
        String base64 = null;
        InputStream in = null;
        try {
            File file = new File(path);
            in = new FileInputStream(file);
            byte[] bytes=new byte[(int)file.length()];
            in.read(bytes);
            base64 = Base64.getEncoder().encodeToString(bytes);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (in != null) {
                try {
                    in.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return base64;
    }




//BASE64解码成File文件
    public static void base64ToFile(String destPath,String base64, String fileName) {
        File file = null;
        //创建文件目录
        String filePath=destPath;
        File  dir=new File(filePath);
        if (!dir.exists() && !dir.isDirectory()) {
            dir.mkdirs();
        }
        BufferedOutputStream bos = null;
        java.io.FileOutputStream fos = null;
        try {
            byte[] bytes = Base64.getDecoder().decode(base64);
            file=new File(filePath+"/"+fileName);
            fos = new java.io.FileOutputStream(file);
            bos = new BufferedOutputStream(fos);
            bos.write(bytes);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (bos != null) {
                try {
                    bos.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (fos != null) {
                try {
                    fos.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }


☛需要注意:标红的base64在这里需要去掉
//原文提供的去除方法  
baseStr = baseStr.replace("data:image/jpeg;base64,", "");//base64解密部分乱码问题(“+” 号,在urlecode编码中会被解码成空格)
//我提供的去除方法
baseStr = data.split(";base64,")[1]

文章到此就结束了,用字符串接收 自定义转换成byte数组与file文件 其下的操作还不是任我行 嘿嘿~~~

此为前端工具类  含有操作cookie,与字符串滤空,格式化日期 文件转base64之类的方法
export default {
    setCookie(cname,cvalue,exdays){
        var d = new Date();
        d.setTime(d.getTime()+(exdays*24*60*60*1000));
        var expires = "expires="+d.toGMTString();
        document.cookie = cname+"="+cvalue+"; "+expires;
    },
    getCookie(cname){
        var name = cname + "=";
        var ca = document.cookie.split(';');
        for(var i=0; i<ca.length; i++) {
            var c = ca[i].trim();
            if (c.indexOf(name)==0) { return c.substring(name.length,c.length); }
        }
        return "";
    },
    empty(str){
        if(str===""||str==undefined||str==null){
            return false;
        }else{
            return true;
        }
    },
    isPwd(str){
        let reg = /^\d{6,8}$/;
        return reg.test(str);
    },
	// 格式化日期
	dateFtt(fmt,date){ 
		var o = {   
			"M+" : date.getMonth()+1,                 //月份   
			"d+" : date.getDate(),                    //日   
			"h+" : date.getHours(),                   //小时   
			"m+" : date.getMinutes(),                 //分   
			"s+" : date.getSeconds(),                 //秒   
			"q+" : Math.floor((date.getMonth()+3)/3), //季度   
			"S"  : date.getMilliseconds()             //毫秒   
		};   
		if(/(y+)/.test(fmt))   
			fmt=fmt.replace(RegExp.$1, (date.getFullYear()+"").substr(4 - RegExp.$1.length));   
		for(var k in o)   
			if(new RegExp("("+ k +")").test(fmt))   
		fmt = fmt.replace(RegExp.$1, (RegExp.$1.length==1) ? (o[k]) : (("00"+ o[k]).substr((""+ o[k]).length)));
		return fmt;   
	},
	// base64
	toBase64(file, fun) {
		//参数file为input获取到的file数组第一项,fun向外传递转换成功的base64编码
		var reader = new FileReader();
		if(file) {
			reader.readAsDataURL(file);
			reader.onload = function() {
				fun(this.result);
			}
		}
    },

}

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值