servlet 接收 base64编码图片上传到服务器 java 代码

java.util.Base64.getEncoder().encodeToString("进制)//编码
java.util.Base64.getDecoder().decode(字符串内容)//解码

import java.util.Base64;
import java.util.Base64.Decoder; 

需要导入这两个类

    public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        
        request.setCharacterEncoding("utf-8");
        response.setContentType("text/html;charset=utf-8");    
        String imgName = request.getParameter("name");        
        String img = request.getParameter("imgbase64");        
        int index = img.lastIndexOf(",");
        if(index != -1) {
            img = img.substring(index+1);
        }//去除ata:image/jpeg;base64,前缀
        Decoder decode = Base64.getDecoder();
        byte[] byteImg = decode.decode(img);//把base64转成字节码
        System.out.println(imgName);
        int hc = imgName.hashCode();
        String hex = Integer.toHexString(hc);//16进制字符串
        /*
         * 创建文件夹
         */
        String root = this.getServletContext().getRealPath("/images/user/");
        System.out.println(root);
        File dirFile = new File(root,"/"+hex.charAt(0)+"/"+hex.charAt(1));//取前16进制的前两个字符串创建二级目录
        dirFile.mkdirs();//创建目录
        String imgNewName = CommonUtils.unid()+".jpg";
        OutputStream out = new FileOutputStream(dirFile+"/"+imgNewName);//保存
        out.write(byteImg);//写入文件
        out.flush();
        out.close();
        //新图片地址
        String newAdd = this.getServletContext().getContextPath()+"/images/user/"+hex.charAt(0)+"\\/"+hex.charAt(1)+"\\/"+imgNewName;
        System.out.println(newAdd);
        
        response.getWriter().write("{\"src\":\""+newAdd+"\"}"); //返回到前端页面
        
    }

  • 2
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值