zoukankan      html  css  js  c++  java
  • 记录一个简单的业务逻辑,将base64格式的文件转成本地文件,把文件名做为id,文件绝对路径做为路径存入数据库,当用户传id的时候直接调用数据库下载这个图片,返回结果为byte[]。

    这篇是记录工作中一个简单的逻辑:

    1.将base64格式的文件转成本地文件,把文件名做为id,文件绝对路径做为路径存入数据库,当用户传id的时候直接调用数据库下载这个图片,返回结果为byte[]。

    base64转图片存本地代码:

    Base64Util base64Util = new Base64Util();
    // 读取配置文件
    String path = AlertMessageManger.class.getClassLoader().getResource("config.properties").getPath();//config.properties配置的是文件要保存的路径
    FileInputStream in;
    in = new FileInputStream(path);
    Properties prop = new Properties();
    prop.load(in);
    // 得到配置文件中的本地路径
    String imagePath = prop.getProperty("path");
    // 雪花算法生成唯一id
    SnowFlakeUtil snowFlake = new SnowFlakeUtil(2, 3);
    long randomNumber18 = snowFlake.nextId();// 18位唯一id
    map.put("file_id", randomNumber18);
    imagePath +="/"+ randomNumber18 + ".jpg";// 本地路径+18位唯一id+后缀                            
    base64Util.generateImage(alarm_image_data, imagePath);
    // base64转文件存到本地 map.put("imagePath", imagePath);
    jArray.add(map);
    String sql = insertSQL(map);//调用插入数据库的方法把数据插入数据库
    executeSql(connection, statement, sql);

    图片下载的controller代码:

    @SuppressWarnings("static-access")
        @RequestMapping(value = "/download", method = RequestMethod.GET, produces = "application/json;charset=utf8")
        public void fileDownload(@RequestParam(value = "file_id", required = false) String file_id,
                @RequestParam(value = "image_size", required = false) String image_size,
                @RequestParam(value = "image_type", required = false) String image_type, HttpSession session,
                HttpServletResponse response) {
            Object[] sessidRet = getSessionId(session);
            JdbcUtil jdbcUtil = new JdbcUtil();
            String sql = null;
            Connection connection = null;
            Statement statement = null;
            ResultSet resultSet = null;
            String msg = null;
            if (file_id == null || "".equals(file_id)) {
                msg = createResultJson(2, "file_id参数不能为空!");
            }
            if (image_size == null || "".equals(image_size)) {
                msg = createResultJson(2, "image_size参数不能为空!");
            }
            if (!image_size.equals("1") && !image_size.equals("2")) {
                msg = createResultJson(2, "image_size值只能为1或者2");
            }
            if (image_type == null || "".equals(image_type)) {
                msg = createResultJson(2, "image_type参数不能为空!");
            }
            if (!image_type.equals("1") && !image_type.equals("2") && !image_type.equals("3")) {
                msg = createResultJson(2, "image_type值只能为1或者2或者3");
            }
            try {
                OutputStream out;
                if (msg != null) {
                    response.reset();
                    response.setHeader("Content-type", "text/html;charset=UTF-8");
                    out = response.getOutputStream();
                    out.write(msg.getBytes("UTF-8"));
                    out.close();
                    return;
                }
                // DowloadFileContent dfc = fileManageService.downloadFile(file_id, sessid);
                long time1 = System.currentTimeMillis();
                sql = "select 数据库 where file_id=" + file_id;
                logger.info("待执行的SQL:" + sql);
                connection = jdbcUtil.getConnection();
                statement = connection.createStatement();
                resultSet = statement.executeQuery(sql);
                long time2 = 0;
                while (resultSet.next()) {
                    String casefile_id = resultSet.getString("file_id");
                    byte[] b = null;
                    if (casefile_id != null) {
                        b = service.downloadSH(file_id, image_type, image_size);
                        long time_ = System.currentTimeMillis();
                        logger.info("SH下载耗时=" + (time_ - time1));
                    }if (b == null) {
                        msg = createResultJson(1, "文件不存在,文件下载失败!");
                        response.setHeader("Content-type", "text/html;charset=UTF-8");
                        out = response.getOutputStream();
                        out.write(msg.getBytes("UTF-8"));
                        out.close();
                        return;
                    } else {
                        response.reset();
                        out = response.getOutputStream();
                        out.write(b, 0, b.length);
                        out.close();
                        long time3 = System.currentTimeMillis();
                        logger.info("写流耗时=" + (time3 - time2));
                        return;
                    }
                }
            } catch (Exception e) {
                logger.error("文件下载失败", e);
                msg = createResultJson(1, "文件下载失败!");
            } finally {
                try {
                    jdbcUtil.CloseConnection(connection, statement, resultSet);
                } catch (SQLException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }
        }

    service代码:

    @SuppressWarnings("static-access")
        @Override
        public byte[] downloadSH(String fileID, String imagetype, String imagesize) throws Exception {
            if (fileID != null) {
                String sql = null;
                Connection connection = null;
                Statement statement = null;
                ResultSet resultSet = null;
                JdbcUtil jdbcUtil = new JdbcUtil();
                sql = "select imagePath from 数据库 where 1=1 and file_id=" + fileID;
                try {
                    connection = jdbcUtil.getConnection();
                    statement = connection.createStatement();
                    resultSet = statement.executeQuery(sql);// 这里是执行SQL语句查询结果并返回结果集
                    String imagePath = null;
                    while (resultSet.next()) {
                        imagePath = resultSet.getString("imagePath");
                    }
                    return InputStream2ByteArray(imagePath);
                } catch (Exception e) {
                    e.printStackTrace();
                    System.err.println("发生异常情况,导致失败,请重试...........");
                } finally {
                    jdbcUtil.CloseConnection(connection, statement, resultSet);
                }
            }
            return null;
        }
      //读取本地图片转化成byte[]
        public byte[] InputStream2ByteArray(String filePath) throws IOException {
            InputStream in = new FileInputStream(filePath);
            byte[] data = toByteArray(in);
            in.close();
            return data;
        }
    
        public byte[] toByteArray(InputStream in) throws IOException {
            ByteArrayOutputStream out = new ByteArrayOutputStream();
            byte[] buffer = new byte[1024 * 4];
            int n = 0;
            while ((n = in.read(buffer)) != -1) {
                out.write(buffer, 0, n);
            }
            return out.toByteArray();
        }
  • 相关阅读:
    window上部署Flask
    PIP超时
    覆盖内敛样式
    解决js导出csv中文乱码
    没有为请求的 URL 配置默认文档,并且没有在服务器上启用目录浏览。
    nuget加载本地包
    DataTable表头对不齐、添加参数等方法总结
    根据class判断
    element-ui的table动态生成表头和数据,且表中数据可编辑
    VScode快捷键、Chrome快捷键知识小总结和状态码
  • 原文地址:https://www.cnblogs.com/wangquanyi/p/11446320.html
Copyright © 2011-2022 走看看