1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380
| package com.jhj.media.service.impl;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper; import com.baomidou.mybatisplus.extension.plugins.pagination.Page; import com.j256.simplemagic.ContentInfo; import com.j256.simplemagic.ContentInfoUtil; import com.jhj.base.exception.UltimateException; import com.jhj.base.model.PageParams; import com.jhj.base.model.PageResult; import com.jhj.base.model.RestResponse; import com.jhj.media.mapper.MediaFilesMapper; import com.jhj.media.model.dto.QueryMediaParamsDto; import com.jhj.media.model.dto.UploadFileParamsDto; import com.jhj.media.model.dto.UploadFileResultDto; import com.jhj.media.model.po.MediaFiles; import com.jhj.media.service.MediaFileService; import io.minio.*; import io.minio.messages.DeleteError; import io.minio.messages.DeleteObject; import lombok.extern.slf4j.Slf4j; import org.apache.commons.codec.digest.DigestUtils; import org.apache.commons.compress.utils.IOUtils; import org.springframework.beans.BeanUtils; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Value; import org.springframework.context.annotation.Lazy; import org.springframework.http.MediaType; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional;
import java.io.*; import java.text.SimpleDateFormat; import java.time.LocalDateTime; import java.util.Date; import java.util.List; import java.util.stream.Collectors; import java.util.stream.Stream;
@Service @Slf4j public class MediaFileServiceImpl implements MediaFileService { @Autowired MediaFilesMapper mediaFilesMapper;
@Autowired MinioClient minioClient;
@Autowired @Lazy MediaFileService currentProxy;
@Value("${minio.bucket.files}") private String bucket_mediafiles;
@Value("${minio.bucket.videofiles}") private String bucket_video;
@Override public PageResult<MediaFiles> queryMediaFiels(Long companyId, PageParams pageParams, QueryMediaParamsDto queryMediaParamsDto) {
LambdaQueryWrapper<MediaFiles> queryWrapper = new LambdaQueryWrapper<>();
Page<MediaFiles> page = new Page<>(pageParams.getPageNo(), pageParams.getPageSize()); Page<MediaFiles> pageResult = mediaFilesMapper.selectPage(page, queryWrapper); List<MediaFiles> list = pageResult.getRecords(); long total = pageResult.getTotal(); PageResult<MediaFiles> mediaListResult = new PageResult<>(list, total, pageParams.getPageNo(), pageParams.getPageSize()); return mediaListResult;
}
@Override public UploadFileResultDto uploadFile(Long companyId, UploadFileParamsDto uploadFileParamsDto, String localFilePath) { String filename = uploadFileParamsDto.getFilename(); String extension = filename.substring(filename.lastIndexOf(".")); String mimeType = getMimeType(extension); String fileMd5 = getFileMd5(new File(localFilePath)); String defaultFolderPath = getDefaultFolderPath(); String objectName = defaultFolderPath + fileMd5 + extension; boolean result = addMediaFilesToMinio(localFilePath, mimeType, bucket_mediafiles, objectName); if(!result){ UltimateException.cast("上传文件失败"); }
MediaFiles mediaFiles = currentProxy.addMediaFilesToDb(companyId, fileMd5, uploadFileParamsDto, bucket_mediafiles, objectName); if(mediaFiles==null){ UltimateException.cast("文件上传后,保存信息失败"); }
UploadFileResultDto uploadFileResultDto = new UploadFileResultDto(); BeanUtils.copyProperties(mediaFiles,uploadFileResultDto); return uploadFileResultDto; }
private String getMimeType(String extension) { if (extension == null) { extension = ""; } ContentInfo extensionMatch = ContentInfoUtil.findExtensionMatch(extension); String mimeType = MediaType.APPLICATION_OCTET_STREAM_VALUE; if (extensionMatch != null) { mimeType = extensionMatch.getMimeType(); } return mimeType; }
private boolean addMediaFilesToMinio(String localFilePath, String mimeType, String bucket, String objectName) { try { minioClient.uploadObject( UploadObjectArgs.builder() .bucket(bucket) .filename(localFilePath) .object(objectName) .contentType(mimeType) .bucket(bucket).build() ); log.debug("上传文件到minio成功,bucket:{},objectName:{}",bucket,objectName); return true; } catch (Exception e) { e.printStackTrace(); log.error("上传文件出错,bucket:{},objectName:{},错误信息:{}",bucket,objectName,e.getMessage()); } return false; } private String getDefaultFolderPath(){ SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd"); String folder = sdf.format(new Date()).replace("-", "/") + "/"; return folder; }
private String getFileMd5(File file){ try(FileInputStream fileInputStream=new FileInputStream(file)){ String fileMd5 = DigestUtils.md5Hex(fileInputStream); return fileMd5; }catch (Exception e){ e.printStackTrace(); return null; } }
@Transactional public MediaFiles addMediaFilesToDb(Long companyId, String fileMd5, UploadFileParamsDto uploadFileParamsDto,String bucket,String objectName){ MediaFiles mediaFiles = mediaFilesMapper.selectById(fileMd5); if (mediaFiles == null){ mediaFiles=new MediaFiles(); BeanUtils.copyProperties(uploadFileParamsDto,mediaFiles); mediaFiles.setId(fileMd5); mediaFiles.setFileId(fileMd5); mediaFiles.setCompanyId(companyId); mediaFiles.setBucket(bucket); mediaFiles.setFilePath(objectName); mediaFiles.setUrl("/"+bucket+"/"+objectName); mediaFiles.setCreateDate(LocalDateTime.now()); mediaFiles.setStatus("1"); mediaFiles.setAuditStatus("002003"); int insert = mediaFilesMapper.insert(mediaFiles); int i=1/0; if(insert<0){ log.error("向数据库保存文件失败,bucket:{},objectName:{}",bucket,objectName); return null; } return mediaFiles; } return mediaFiles; }
@Override public RestResponse<Boolean> checkFile(String fileMd5) { MediaFiles mediaFiles = mediaFilesMapper.selectById(fileMd5); if(mediaFiles!=null){ String bucket = mediaFiles.getBucket(); String filePath = mediaFiles.getFilePath(); GetObjectArgs getObjectArgs = GetObjectArgs.builder() .bucket(bucket) .object(filePath) .build();
try { FilterInputStream inputStream = minioClient.getObject(getObjectArgs); if(inputStream!=null){ return RestResponse.success(true); } } catch (Exception e) { e.printStackTrace(); } } return RestResponse.success(false); }
@Override public RestResponse<Boolean> checkChunk(String fileMd5, int chunkIndex) { String chunkFileFolderPath = getChunkFileFolderPath(fileMd5)+chunkIndex; GetObjectArgs getObjectArgs = GetObjectArgs.builder() .bucket(bucket_video) .object(chunkFileFolderPath) .build(); try { FilterInputStream inputStream = minioClient.getObject(getObjectArgs); if(inputStream!=null){ return RestResponse.success(true); } } catch (Exception e) { e.printStackTrace(); } return RestResponse.success(false); }
@Override public RestResponse uploadChunk(String fileMd5, int chunk, String localChunkFilePath) { String mimeType = getMimeType(null); boolean b = addMediaFilesToMinio(localChunkFilePath, mimeType, bucket_video, getChunkFileFolderPath(fileMd5) + chunk); if(!b){ return RestResponse.validfail("上传分块文件失败",false); } return RestResponse.success(true); }
@Override public RestResponse mergechunks(Long companyId, String fileMd5, int chunkTotal, UploadFileParamsDto uploadFileParamsDto) { String chunkFileFolderPath = getChunkFileFolderPath(fileMd5); List<ComposeSource> sources = Stream.iterate(0, i -> ++i).limit(chunkTotal).map(i -> { return ComposeSource.builder().bucket(bucket_video).object(chunkFileFolderPath + i).build(); }).collect(Collectors.toList());
String filename = uploadFileParamsDto.getFilename(); String extension = filename.substring(filename.lastIndexOf(".")); String filePathByMd5 = getFilePathByMd5(fileMd5, extension); ComposeObjectArgs testbucket = ComposeObjectArgs.builder().bucket(bucket_video) .object(filePathByMd5) .sources(sources) .build(); try { minioClient.composeObject(testbucket); } catch (Exception e) { e.printStackTrace(); log.error("合并文件出错,bucket:{},onjectName:{},错误信息:{}",bucket_video,filePathByMd5,e.getMessage()); return RestResponse.validfail("合并文件异常",false); } File file = downloadFileFromMinIo(bucket_video, filePathByMd5); try(FileInputStream fileInputStream = new FileInputStream(file)){ String mergeFile_md5 = DigestUtils.md5Hex(fileInputStream); if(!fileMd5.equals(mergeFile_md5)){ log.error("校验合并文件md5值不一致,原始文件:{},合并文件:{}",fileMd5,mergeFile_md5); return RestResponse.validfail("文件校验失败",false); } uploadFileParamsDto.setFileSize(file.length()); }catch (Exception e){ return RestResponse.validfail("文件校验失败",false); } MediaFiles mediaFiles = currentProxy.addMediaFilesToDb(companyId, fileMd5, uploadFileParamsDto, bucket_video, filePathByMd5); if(mediaFiles==null){ return RestResponse.validfail("文件入库失败",false); } clearChunkFiles(chunkFileFolderPath,chunkTotal);
return RestResponse.success(true); }
private String getChunkFileFolderPath(String fileMd5){ return fileMd5.substring(0,1)+"/"+fileMd5.substring(1,2)+"/"+fileMd5+"/"+"chunk"+"/"; }
private String getFilePathByMd5(String fileMd5,String fileExt){ return fileMd5.substring(0,1)+"/"+fileMd5.substring(1,2)+"/"+fileMd5+"/"+fileMd5+fileExt; }
public File downloadFileFromMinIo(String bucket,String objectName){ File minioFile=null; FileOutputStream outputStream=null; try { InputStream inputStream = minioClient.getObject(GetObjectArgs.builder().bucket(bucket).object(objectName).build()); minioFile=File.createTempFile("minio",".merge"); outputStream = new FileOutputStream(minioFile); IOUtils.copy(inputStream,outputStream); return minioFile; } catch (Exception e) { e.printStackTrace(); }finally { try { outputStream.close(); } catch (IOException e) { e.printStackTrace(); } } return minioFile; }
private void clearChunkFiles(String chunkFileFolderPath, int chunkTotal){ Iterable<DeleteObject> objects=Stream.iterate(0,i->++i).limit(chunkTotal).map(i->{ return new DeleteObject(chunkFileFolderPath+i); }).collect(Collectors.toList()); RemoveObjectsArgs removeObjectArgs = RemoveObjectsArgs.builder().bucket(bucket_video).objects(objects).build(); Iterable<Result<DeleteError>> results = minioClient.removeObjects(removeObjectArgs); results.forEach(f->{ try { DeleteError deleteError = f.get(); } catch (Exception e){ e.printStackTrace(); } }); } }
|