springboot文件上传之MultipartFile(图片)转base64

public ImageIdentificationResult imageIdentification(String api_id, String api_secret, MultipartFile file,
                                                         String group_id)
    {
        logger.info("start to image identification. api_id: {}, api_secret: {}, group_id: {}.", api_id, api_secret,
            group_id);

        //需要将file转为base64
        String fileStr = "";
        if (!file.isEmpty())
        {
            BASE64Encoder encoder = new BASE64Encoder();
            // 通过base64来转化图片
            try
            {
                fileStr = encoder.encode(file.getBytes());
            }
            catch (IOException e)
            {
                logger.error("encode file catch exception.");
                ImageIdentificationResult imageIdentificationResult = new ImageIdentificationResult();
                imageIdentificationResult.setStatus(e.getLocalizedMessage());
                return imageIdentificationResult;
            }
        }
        else
        {
            logger.error("file is empty.");
            ImageIdentificationResult imageIdentificationResult = new ImageIdentificationResult();
            imageIdentificationResult.setStatus("picture is invalid");
            return imageIdentificationResult;
        }

        ImageIdentificationParam imageIdentificationParam = new ImageIdentificationParam();
        imageIdentificationParam.setApi_id(api_id);
        imageIdentificationParam.setApi_secret(api_secret);
        imageIdentificationParam.setFile(fileStr);
        imageIdentificationParam.setGroup_id(group_id);

        try
        {
            return this.faceService.imageIdentification(imageIdentificationParam);
        }
        catch (Exception e)
        {
            logger.error("imageIdentification catch exception. cause: ", e);
            ImageIdentificationResult imageIdentificationResult = new ImageIdentificationResult();
            imageIdentificationResult.setStatus(e.getLocalizedMessage());
            return imageIdentificationResult;
        }
    }

需要注意的是,获取到的fileStr中可能会有换行符之类的,需要用replaceAll方法替换掉

你可能感兴趣的:(springboot)