java_图片转base64字符串

博客介绍了两种将文件转换为Base64编码的方法。一是直接获取文件并转换,通过Spring的请求映射处理文件,读取文件字节数组后进行Base64编码;二是从本地获取文件转换,根据配置路径读取文件,存在则进行Base64编码。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

1、直接获取文件,转based4

/**
     * 2017-7-17
     * @param id
     * @return
     */
    @RequestMapping("add")
    public void add(CqscBrayData cqscBrayData,MultipartHttpServletRequest request,
            HttpServletResponse response){
        response.setContentType("text/html; charset=utf-8");
        MultipartFile fileCrl = request.getFile("myUploadCrl");
        CommonsMultipartFile cf= (CommonsMultipartFile)fileCrl; 
        DiskFileItem fi = (DiskFileItem)cf.getFileItem(); 
        File f = fi.getStoreLocation();
        if(fi.getSize() != 0){
            byte[] bs = null;
            try {
                bs = FileUtils.readFileToByteArray(f);
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
            // 加密为base64编码字符串
            BASE64Encoder encoder = new BASE64Encoder();
            String bsCrl = encoder.encode(bs);
            System.out.println(bsCrl);
            cqscBrayData.setCrlBase64(bsCrl);
        }

        try {
            om.writeValue(response.getWriter(), map);
            response.getWriter().flush();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }finally {
            try {
                response.getWriter().close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

 

2、从本地获取文件,转based4

public static String getBase64Path(String img_path){
        String photopath = PropertiesUtil.getProp("photoPath");
        String replac = photopath.substring(3);
        String path = photopath.replace(replac, img_path);
        File file = new File(path);
        byte[] bs = null;
        if(file.exists()){
            try {
                bs = FileUtils.readFileToByteArray(file);
                // 加密为base64编码字符串
                BASE64Encoder encoder = new BASE64Encoder();
                String baseStr = encoder.encode(bs);
                System.out.println(baseStr);
            } catch (IOException e1) {
                e1.printStackTrace();
            }
        }
        return path;
    }

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值