首页 > 其他分享 >使用developer API压缩

使用developer API压缩

时间:2024-03-02 11:22:21浏览次数:27  
标签:String 压缩 connection API file error new developer

key

  /**
     * 中转压缩url
     */
    public final static String TINIFY_URL = "https://api.tinify.com/shrink";

    /**
     * tinify apiKey
     */
    public final static String API_KET = "xxxxx";

 

controller

@PostMapping("/upload")
    public DataResult<Object> upload(MultipartFile file) {
        try {
            return R.success(TransferUtils.compressFile(file.getInputStream()));
        } catch (DefaultException e) {
            log.error("上传文件压缩出错:{}", e.getMessage());
            return R.error("上传文件压缩出错");
        } catch (Exception e) {
            log.error("上传文件压缩出错:{}", e, e);
            return R.error("上传文件压缩出错");
        }
    }

 

业务层

public static JsonNode compressFile(InputStream inputStream) {
        HttpURLConnection connection = null;
        try {
            URL apiUrl = new URL(ImageConstant.TINIFY_URL);
            connection = (HttpURLConnection) apiUrl.openConnection();
            connection.setRequestMethod("POST");
            connection.setDoOutput(true);
            connection.setRequestProperty("Authorization", "Basic " + Base64.getEncoder().encodeToString(("api:" + ImageConstant.API_KET).getBytes()));

            try (InputStream in = inputStream;
                 OutputStream out = connection.getOutputStream()) {
                byte[] buffer = new byte[1024];
                int bytesRead;
                while ((bytesRead = in.read(buffer)) != -1) {
                    out.write(buffer, 0, bytesRead);
                }
            }
            int responseCode = connection.getResponseCode();
            if (responseCode == HttpURLConnection.HTTP_CREATED) {
                InputStream responseStream = connection.getInputStream();
                BufferedReader reader = new BufferedReader(new InputStreamReader(responseStream));
                // tinify API 返回的JSON数据
                String response = reader.readLine();
                ObjectMapper objectMapper = new ObjectMapper();
                return objectMapper.readTree(response);
            } else {
                try (InputStream errorStream = connection.getErrorStream()) {
                    if (errorStream != null) {
                        BufferedReader errorReader = new BufferedReader(new InputStreamReader(errorStream));
                        StringBuilder errorMessage = new StringBuilder();
                        String line;
                        while ((line = errorReader.readLine()) != null) {
                            errorMessage.append(line);
                        }
                        log.error("文件压缩失败,响应码:{},错误信息:{}", responseCode, errorMessage.toString());
                    } else {
                        log.error("文件压缩失败,响应码:{},但未收到错误信息", responseCode);
                    }
                }
                throw new DefaultException("文件压缩异常");
            }
        } catch (IOException e) {
            e.printStackTrace();
        } catch (Exception e) {
            log.error("压缩异常", e);
            e.printStackTrace();
        } finally {
            if (connection != null) {
                connection.disconnect();
            }
        }
        throw new DefaultException("文件压缩异常");
    }

 

压缩后上传到oss中

controller

@PostMapping("/compress/upload")
    public DataResult<Object> compressFileUpload(@RequestBody MultipartFile file, Integer inPrivate) {
        String rs;
        try {
            if (file != null && file.getBytes().length > 0) {
                String userId = UserUtils.getUserId();
                long t1 = System.currentTimeMillis();
                ObjectMetadata meta = null;
                meta = new ObjectMetadata();
                Map<String, String> map = new HashMap<>();
                map.put("fileName", URLEncoder.encode(file.getOriginalFilename()));
                meta.setUserMetadata(map);
                meta.setContentType(file.getContentType());

                String fileName = OSSClientUtil.handleFormat(file, inPrivate, userId);
                rs = OSSClientUtil.compressUpload(fileName, file, meta, inPrivate);
                if (rs != null) {
                    SlOssFile slOssFile = fileOperatService.addOssFile(file, fileName, rs);
                    long t2 = System.currentTimeMillis();
                    log.info("上传{}耗时{}秒", file.getOriginalFilename(), (t2 - t1) / 1000);
                    return R.success(slOssFile);
                }
                long t2 = System.currentTimeMillis();
                log.info("上传{}耗时{}秒", file.getOriginalFilename(), (t2 - t1) / 1000);
            }
            return R.error("文件不存在");
        } catch (DefaultException e) {
            log.error("压缩图片上传至oss出错:{}", e.getMessage());
            return R.error("压缩图片上传至oss出错");
        } catch (Exception e) {
            log.error("压缩图片上传至oss出错:{}", e, e);
            return R.error("压缩图片上传至oss出错");
        }
    }

 

 

public static String compressUpload(String fileKey, MultipartFile file, ObjectMetadata meta, Integer inPrivate){
        HttpURLConnection connection = null;
        try {
            URL apiUrl = new URL(TinifyConstant.TINIFY_URL);
            connection = (HttpURLConnection) apiUrl.openConnection();
            connection.setRequestMethod("POST");
            connection.setDoOutput(true);
            connection.setRequestProperty("Authorization", "Basic " + Base64.getEncoder().encodeToString(("api:" + TinifyConstant.API_KET).getBytes()));

            try (InputStream in = file.getInputStream();
                 OutputStream out = connection.getOutputStream()) {
                byte[] buffer = new byte[1024];
                int bytesRead;
                while ((bytesRead = in.read(buffer)) != -1) {
                    out.write(buffer, 0, bytesRead);
                }
            }
            int responseCode = connection.getResponseCode();
            if (responseCode == HttpURLConnection.HTTP_CREATED) {
                InputStream responseStream = connection.getInputStream();
                BufferedReader reader = new BufferedReader(new InputStreamReader(responseStream));
                // tinify API 返回的JSON数据
                String response = reader.readLine();
                ObjectMapper objectMapper = new ObjectMapper();
                JsonNode jsonNode = objectMapper.readTree(response);
                String url = jsonNode.get("output").get("url").asText();
                URL ossUrl = new URL(url);
                HttpURLConnection ossConnection = (HttpURLConnection) ossUrl.openConnection();
                ossConnection.setRequestMethod("GET");
                try (InputStream compressedInputStream = ossConnection.getInputStream()) {
                    if (inPrivate.equals(1)) {
                        PutObjectResult putObjectResult = getOssClientPrivateInternal().putObject(VIDEO_BUCKET_NAME, fileKey, compressedInputStream, meta);
                        boolean b = getOssClientPrivateInternal().doesObjectExist(VIDEO_BUCKET_NAME, fileKey);
                        if (b) {
                            return VIDEO_ENDPOINT + "/" + fileKey;
                        }
                    } else {
                        PutObjectResult putObjectResult = getOssClientInternal().putObject(BUCKET_NAME, fileKey, compressedInputStream, meta);
                        boolean objectExists = getOssClientInternal().doesObjectExist(BUCKET_NAME, fileKey);
                        if (objectExists) {
                            setFileAuth(fileKey, CannedAccessControlList.PublicRead);
                            return ENDPOINT + "/" + fileKey;
                        }
                    }
                }
             } else {
                 try (InputStream errorStream = connection.getErrorStream()) {
                      if (errorStream != null) {
                            BufferedReader errorReader = new BufferedReader(new InputStreamReader(errorStream));
                            StringBuilder errorMessage = new StringBuilder();
                            String line;
                            while ((line = errorReader.readLine()) != null) {
                                errorMessage.append(line);
                            }
                            log.error("文件压缩失败,响应码:{},错误信息:{}", responseCode, errorMessage.toString());
                      } else {
                          log.error("文件压缩失败,响应码:{},但未收到错误信息", responseCode);
                      }
                 }
                 throw new DefaultException("文件压缩异常");
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

拿到压缩后的输入流上传oss即可,inPrivate为1表示oss的加密上传,为0表示非加密上传

 

标签:String,压缩,connection,API,file,error,new,developer
From: https://www.cnblogs.com/ckfeng/p/18048429

相关文章

  • Lazada电商api接口 获取商品详情 数据采集
    iDataRiver平台https://www.idatariver.com/zh-cn/提供开箱即用的Lazada电商数据采集API,供用户按需调用。接口使用详情请参考Lazada接口文档接口列表获取用户详情参数类型是否必填默认值示例值描述apikeystring是idr_***从控制台里复制apikeyitem_idn......
  • 并查集(模板介绍+路径压缩)
    并查集(模板介绍+路径压缩)题面P3367并查集题目描述如题,现在有一个并查集,你需要完成合并和查询操作。第一行包含两个整数N,M,表示共有N个元素和M个操作。接下来M行,每行包含三个整数Z,X,Y。当Z=1时,将X与Y所在的集合合并。当Z=2时,输出Z与Y是否在同一集合内,是的输出Y;否则输出N......
  • 如何安装earthengine-api
       第一篇 直接使用 pipinstallearthengine-api命令提示找不到相匹配的earthengine-api版本。发现earthengine-api只支持64位的python。 于是,去查看了我电脑的操作系统是多少位的,打开cmd,输入systeminfo 小小的脑袋大大的疑惑,电脑的操作系统是64位的呀。......
  • 接口写完想快速压力测试?试试Apipost一键压测功能
    背景研发同学在调试完成某些接口后需要验证一下高并发情况下的接口运行情况。这时候必须得跟测试同学协调一下,但这来来回回也有点麻烦,而实际上,这个工作量并不算太大。所以Apipost也是推出了一键压测功能来解决这个痛点场景。这篇文章给大家介绍Apipost的一键压测功能。使用方法......
  • API调试IDEA插件用这款就够了
    IDEA是一款功能强大的集成开发环境(IDE),它可以帮助开发人员更加高效地编写、调试和部署软件应用程序。我们在编写完接口代码后需要进行接口调试等操作,一般需要打开额外的调试工具。今天给大家介绍一款IDEA插件:Apipost-Helper-2.0。代码写完直接编辑器内调试、还支持生成接口文档、......
  • ApiFox-token
    标题:ApiFox-token功能:使用ApiFox->1-登入接口->2-获取token-->3-token变成"环境变量"-->4-后面的接口使用这个"token"1-登入功能(按步骤操作)2-登入功能(附加:后置操作)2.5-补充重点是:JsonPath表达式:$.data.token对照下面‘图片的返回值’......
  • 图像压缩在上传客户端以及下载客户端的实现
    本地图像在上传服务器时,由于所占存储空间比较大,一般会进行压缩上传:一般分为前端压缩和后端压缩。前端压缩:在上传之前在客户端的进行压缩,然后再上传。后端压缩:在服务器端接收到上传的图片后,在服务器端对图片进行压缩。通常进行先进行前端压缩,然后如果图像仍然太大,则会进行二次......
  • Tiktok api接口 获取视频列表、用户详情,视频无水印数据采集
    iDataRiver平台https://www.idatariver.com/zh-cn/提供开箱即用的Tiktok数据采集API,供用户按需调用。接口使用详情请参考Tiktok接口文档接口列表1.获取用户详情参数类型是否必填默认值示例值描述apikeystring是idr_***从控制台里复制apikeyuser_idnu......
  • 搭建一个大模型API服务
    搭建一个大模型API服务本文将介绍如何使用SWIFT框架搭建一个大模型API服务,以方便后续做RAG、Agent的开发工作。环境准备基础环境操作系统:Ubuntu18.04.5LTS(GNU/Linux3.10.0-1127.el7.x86_64x86_64)Anaconda3:Anaconda3-2023.03-1-Linux-x86_64根据服务器网络情况配置好......
  • java 解压缩文件
    java解压缩文件解压缩zip文件privatestaticfinalintBUFFER_SIZE=2*1024;publicstaticvoidzipUncompress(StringinputFile)throwsException{FilesrcFile=newFile(inputFile);//判断源文件是否存在if(!srcFile.exis......