文件通过后台判断获取,并转成base64格式返给前端(二)

博客内容讲述了在前端和后端代码中如何处理本地图片的访问,通过Base64编码实现图片数据的传输。前端通过指定URL加载图片,后端则读取文件并转换为Base64字符串返回。在处理过程中,检查了文件类型和UID的有效性,确保了图片拦截和权限校验。
摘要由CSDN通过智能技术生成

接上一篇写完,接下来测试时候,发现了问题,图片就在本地,部署的服务器上存储着,不需要通过http所谓的网络请求,好吧,改代码,获取本地图片:
前端代码:

<img src="localhost:xxxx/xxxx/test.jpg?UID=xxxxxx&type=jpg"/>

后端代码:

package com.xxxxx.xxxxx.xxxxx.controller;

import com.xxxxx.micro.common.util.ResultUtil;
import com.xxxxx.micro.common.web.BaseController;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.rmi.server.UID;
import java.util.Map;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import sun.misc.BASE64Encoder;

/**
 * @ClassName: PictureController
 * @Description:
 * @author: xxxxx
 * @create: 2021/12/3 14:28
 */
@RestController
@Api(tags = "接口改造-图片拦截")
@Slf4j
@RequestMapping("/weblogic")
public class PictureController extends BaseController {

    @GetMapping("/app/eomdoc/{url}")
    @ApiOperation(value = "查询图片,根据uid是否有效进行拦截", notes = "查询图片,根据uid是否有效进行拦截")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "UID", value = "用户UID", required = true, paramType = "query"),
            @ApiImplicitParam(name = "type", value = "文件格式类型", required = true, paramType = "query"),
            @ApiImplicitParam(name="url", value="文件名称", required=true, paramType="query")
    })
    public String weblogic(@PathVariable String url,@RequestParam String type, String UID){

        Map<String, Object> params = this.getParams();

        if (StringUtils.isBlank(url) || StringUtils.isBlank(type) ){
            return this.responseJson(ResultUtil.error("参数缺失不完整"),null,null);
        }

        try {
            log.info("******查询的文件类型是:" + type + "*********************");
            //判断文件类型(jpg,jpeg,bmp,png,gif,tiff),如果是图片类型--进行拦截,校验UID
            if(StringUtils.equalsIgnoreCase("jpg",type) || StringUtils.equalsIgnoreCase("jpeg",type) || StringUtils.equalsIgnoreCase("bmp",type) || StringUtils.equalsIgnoreCase("png",type) || StringUtils.equalsIgnoreCase("gif",type) || StringUtils.equalsIgnoreCase("tiff",type)){
                //参数-UID判空
                if (StringUtils.isBlank(UID)){
                    return this.responseJson(ResultUtil.error("参数UID缺失"),null,null);
                }
                //查询当前登录人
                Map<String, Object> loginUser = this.getLoginUser();
                if (loginUser == null){
                    return this.responseJson(ResultUtil.error("查询当前登录人失败"),null,null);
                }
            }

            String path = "/weblogic/xxxxx/xxxxx/" + url + "." + type;
            log.info("******文件路径是:" + path + "*********************");

            File files = new File(path);
            //文件判空
			if (null == files || 0 == files.length() || !files.exists()) {
				System.out.println("文件为空!");
				log.error("文件为空!");
				return "文件为空";
			}

			//将文件转换为base64流
			FileInputStream inputFile = new FileInputStream(files);
			byte[] buffer = new byte[(int) files.length()];
			inputFile.read(buffer);
			inputFile.close();

            // 对字节数组Base64编码
            System.out.print(new BASE64Encoder().encode(buffer));
            log.info("*****转base64:",new BASE64Encoder().encode(buffer));
            String base64 = "data:image/jpg;base64,"+ new BASE64Encoder().encode(buffer);

            return base64;
        } catch (Exception e) {
            log.error("转base64失败",e);
            return "转base64失败";
        }
    }

}

返回结果如下:截取了前小半部分结果,只是做展示。

data:image/jpg;base64,iVBORw0KGgoAAAANSUhEUgAABdwAAApsCAYAAADUty/4AAAAAXNSR0IArs4c6QAAAARnQU1BAACx jwv8YQUAAAAJcEhZcwAAEnQAABJ0Ad5mH3gAAAA4ZVhJZk1NACoAAAAIAAGHaQAEAAAAAQAAABoA AAAAAAKgAgAEAAAAAQAABdygAwAEAAAAAQAACmwAAAAAHAzaygAA/2FJREFUeF7s3QecXWWdP/4n vfeE9EJoCQQIHSmKXcoKigV1xS42XPe/q6uibtFdd/W3u67oKroWrFgAUYoiglKU3hJaGqSRhIT0 Xv/3ufNcZubmzsydmWcmU95vXuc15zn3zpyZm2HuOZ/zPd+nx+i7L98XAAAAAACAVumZPgIAAAAA AK0gcAcAAAAAgAwE7gAAAAAAkIHAHQAAAAAAMhC4AwAAAABABgJ3AAAAAADIQOAOAAAAAAAZCNwB AAAAACADgTsAAAAAAGQgcAcAAAAAgAwE7gAAAAAAkIHAHQAAAAAAMhC4AwAAAABABgJ3AAAAAADI QOAOAAAAQIczrHe/tAbQeQjcAQAAAOhwLhl7bHjLmJlpBNA5CNwBAAAA6JC+Ov3lQnegUxG4AwAA ANBhCd2BzkTgDgAAAECHJnQHOguBOwAAAAAdntAd6AwE7gAAAAB0CkJ3oKPrMfruy/eldaAdnTZ0 YpjSb0iY3G9o2lLfht07wtyta8KyHZvCkh0b01YAAADoHj4x8eTw8Uknp1F9H130h/DT1U+kEUDH IXCHdjCl39Bw2tAJ4fQhE8PpQyc2GLI35q6Ny8NdmwpL4eOfCwsAAAB0ZY0F7pHQHeiIBO7QRob1 7hfePHpG8Va3WQNHp615bNizI9y0dlG4YtUjYe6WNWkrAAAAdB3lgfvGPTvD0F5906iG0J2mvHL4 1NCj8F+0aPuGsGD7uuJ6RxQLNt8/7phw+tBJ2bOk7qRUtPqtlY8UO0i0N4E7ZBb/OH584knhonbq Kbd0x8bwpeX3hqtWP5m2AAAAQOdXHri/Y/6NxW1HlQWRnSF0n95/WBhS52LBml3bwvKdm9OodeKd.........
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值