图片文件作为接口参数,api调用实现登录页背景图更换

1.前端更换背景图,传递到后端

后端接收的参数:HttpServletRequest request, MultipartFile uploadImg

uploadImg是图片文件,可以根据需求对图片文件的大小和图片格式作自定义要求。

            File tempFile = File.createTempFile("temp", ".png");
            uploadImg.transferTo(tempFile);

创建临时文件,MulipartFile通过transferTo存入到临时文件中。

2.本地图片的更换

通过Apache的FileUtils操作旧文件,将旧文件删除;

            // 获取旧文件
            File oldFile = new File(targetFilePath);
            FileUtils.forceDeleteOnExit(oldFile);
            FileUtils.copyFile(tempFile, new File(targetFilePath));

首先通过request获取到当前背景图片的位置即targetFilePath;获取到旧文件,并通过FileUtils删除掉旧文件。

将临时文件放到目标文件目录即可,copyFile.

3.调用接口,更新其他服务节点下的图片--图片文件转换

    @Override
    public String getImageByte(HttpServletRequest request) {
        String targetFilePath = getTargetPath(request);
        try (InputStream inputStream = new FileInputStream(targetFilePath);) {
            byte[] data = new byte[inputStream.available()];
            inputStream.read(data);
            return new String(Base64.getEncoder().encode(data));
        } catch (FileNotFoundException e) {
            LOG.error("Get background image fail.{}", e);
        } catch (IOException e) {
            LOG.error("Get background image fail.{}", e);
        }
        return new String();
    }

图片的传递是将图片转换为byte[],然后通过Base64编码获得参数;

4.接口接收图片参数,对本地文件进行更新

try{
            byte[] image = Base64.getDecoder().decode(imageData.getString("imageData"));
            InputStream inputStream = new ByteArrayInputStream(image);
            try {
                File tempFile = File.createTempFile("temp", ".png");
                try (FileOutputStream fos = new FileOutputStream(tempFile)) {
                    byte[] buf = new byte[1024];
                    while (inputStream.read(buf) != -1) {
                        fos.write(buf);
                    }
                } catch (Exception e) {
                    LOG.debug("Parse image data failed.", e);
                }
                this.backgroundImageService.background(request, tempFile);
            } catch (IOException e) {
                LOG.debug("Parse image data failed.", e);
            }
            return ResultBuilder.success(ResultCodeEnum.SUCCESS, ResultMessage.SUCCESS);
        } catch (Exception e) {
            LOG.error("Base64 decode image data error,check request param.", e);
        }

5.遇到报错

Caused by: java.lang.IllegalArgumentException: Illegal base64 character 7b

Caused by:java.lang.IllegalArgumentException: Illegal base64 character 5b

原因:原因就是base64解密参数不正确,一般注意byte[]直接toString转换成字符串,实际得到的是byte[]数组的内存地址。

应该new String(byte);这样来转换类型。

6.这样做目前来说可以正常实现功能,后续问题,后续更新

 

交流QQ:740273040

你可能感兴趣的:(java后端-技术)