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