use of run.halo.app.model.support.UploadResult in project halo by ruibaby.
the class TencentCosFileHandler method upload.
@Override
public UploadResult upload(MultipartFile file) {
Assert.notNull(file, "Multipart file must not be null");
// Get config
String protocol = optionService.getByPropertyOfNonNull(TencentCosProperties.COS_PROTOCOL).toString();
String domain = optionService.getByPropertyOrDefault(TencentCosProperties.COS_DOMAIN, String.class, "");
String region = optionService.getByPropertyOfNonNull(TencentCosProperties.COS_REGION).toString();
String secretId = optionService.getByPropertyOfNonNull(TencentCosProperties.COS_SECRET_ID).toString();
String secretKey = optionService.getByPropertyOfNonNull(TencentCosProperties.COS_SECRET_KEY).toString();
String bucketName = optionService.getByPropertyOfNonNull(TencentCosProperties.COS_BUCKET_NAME).toString();
String source = optionService.getByPropertyOrDefault(TencentCosProperties.COS_SOURCE, String.class, "");
String styleRule = optionService.getByPropertyOrDefault(TencentCosProperties.COS_STYLE_RULE, String.class, "");
String thumbnailStyleRule = optionService.getByPropertyOrDefault(TencentCosProperties.COS_THUMBNAIL_STYLE_RULE, String.class, "");
COSCredentials cred = new BasicCOSCredentials(secretId, secretKey);
Region regionConfig = new Region(region);
ClientConfig clientConfig = new ClientConfig(regionConfig);
// Init OSS client
COSClient cosClient = new COSClient(cred, clientConfig);
StringBuilder basePath = new StringBuilder(protocol);
if (StringUtils.isNotEmpty(domain)) {
basePath.append(domain).append(URL_SEPARATOR);
} else {
basePath.append(bucketName).append(".cos.").append(region).append(".myqcloud.com").append(URL_SEPARATOR);
}
try {
FilePathDescriptor pathDescriptor = new FilePathDescriptor.Builder().setBasePath(basePath.toString()).setSubPath(source).setAutomaticRename(true).setRenamePredicate(relativePath -> attachmentRepository.countByFileKeyAndType(relativePath, AttachmentType.TENCENTCOS) > 0).setOriginalName(file.getOriginalFilename()).build();
// Upload
ObjectMetadata objectMetadata = new ObjectMetadata();
// 提前告知输入流的长度, 否则可能导致 oom
objectMetadata.setContentLength(file.getSize());
// 设置 Content type, 默认是 application/octet-stream
objectMetadata.setContentType(file.getContentType());
PutObjectResult putObjectResponseFromInputStream = cosClient.putObject(bucketName, pathDescriptor.getRelativePath(), file.getInputStream(), objectMetadata);
if (putObjectResponseFromInputStream == null) {
throw new FileOperationException("上传附件 " + file.getOriginalFilename() + " 到腾讯云失败 ");
}
String fullPath = pathDescriptor.getFullPath();
// Response result
UploadResult uploadResult = new UploadResult();
uploadResult.setFilename(pathDescriptor.getName());
uploadResult.setFilePath(StringUtils.isBlank(styleRule) ? fullPath : fullPath + styleRule);
uploadResult.setKey(pathDescriptor.getRelativePath());
uploadResult.setMediaType(MediaType.valueOf(Objects.requireNonNull(file.getContentType())));
uploadResult.setSuffix(pathDescriptor.getExtension());
uploadResult.setSize(file.getSize());
// Handle thumbnail
handleImageMetadata(file, uploadResult, () -> {
if (ImageUtils.EXTENSION_ICO.equals(pathDescriptor.getExtension())) {
uploadResult.setThumbPath(fullPath);
return fullPath;
} else {
return StringUtils.isBlank(thumbnailStyleRule) ? fullPath : fullPath + thumbnailStyleRule;
}
});
return uploadResult;
} catch (Exception e) {
throw new FileOperationException("附件 " + file.getOriginalFilename() + " 上传失败(腾讯云)", e);
} finally {
cosClient.shutdown();
}
}
use of run.halo.app.model.support.UploadResult in project halo by ruibaby.
the class MinioFileHandler method upload.
@NonNull
@Override
public UploadResult upload(@NonNull MultipartFile file) {
Assert.notNull(file, "Multipart file must not be null");
// Get config
String endpoint = optionService.getByPropertyOfNonNull(MinioProperties.ENDPOINT).toString();
String accessKey = optionService.getByPropertyOfNonNull(MinioProperties.ACCESS_KEY).toString();
String accessSecret = optionService.getByPropertyOfNonNull(MinioProperties.ACCESS_SECRET).toString();
String bucketName = optionService.getByPropertyOfNonNull(MinioProperties.BUCKET_NAME).toString();
String source = optionService.getByPropertyOrDefault(MinioProperties.SOURCE, String.class, "");
String region = optionService.getByPropertyOrDefault(MinioProperties.REGION, String.class, "us-east-1");
endpoint = StringUtils.appendIfMissing(endpoint, HaloConst.URL_SEPARATOR);
MinioClient minioClient = MinioClient.builder().endpoint(endpoint).credentials(accessKey, accessSecret).region(region).build();
try {
FilePathDescriptor pathDescriptor = new FilePathDescriptor.Builder().setBasePath(endpoint + bucketName).setSubPath(source).setAutomaticRename(true).setRenamePredicate(relativePath -> attachmentRepository.countByFileKeyAndType(relativePath, AttachmentType.MINIO) > 0).setOriginalName(file.getOriginalFilename()).build();
PutObjectArgs putObjectArgs = PutObjectArgs.builder().contentType(file.getContentType()).bucket(bucketName).stream(file.getInputStream(), file.getSize(), -1).object(pathDescriptor.getRelativePath()).build();
minioClient.ignoreCertCheck();
minioClient.putObject(putObjectArgs);
UploadResult uploadResult = new UploadResult();
uploadResult.setFilename(pathDescriptor.getName());
uploadResult.setFilePath(pathDescriptor.getFullPath());
uploadResult.setKey(pathDescriptor.getRelativePath());
uploadResult.setMediaType(MediaType.valueOf(Objects.requireNonNull(file.getContentType())));
uploadResult.setSuffix(pathDescriptor.getExtension());
uploadResult.setSize(file.getSize());
// Handle thumbnail
handleImageMetadata(file, uploadResult, pathDescriptor::getFullPath);
return uploadResult;
} catch (Exception e) {
log.error("upload file to MINIO failed", e);
throw new FileOperationException("上传附件 " + file.getOriginalFilename() + " 到 MinIO 失败 ", e).setErrorData(e.getMessage());
}
}
use of run.halo.app.model.support.UploadResult in project halo by ruibaby.
the class UpOssFileHandler method upload.
@Override
public UploadResult upload(MultipartFile file) {
Assert.notNull(file, "Multipart file must not be null");
String source = optionService.getByPropertyOfNonNull(UpOssProperties.OSS_SOURCE).toString();
String password = optionService.getByPropertyOfNonNull(UpOssProperties.OSS_PASSWORD).toString();
String bucket = optionService.getByPropertyOfNonNull(UpOssProperties.OSS_BUCKET).toString();
String protocol = optionService.getByPropertyOfNonNull(UpOssProperties.OSS_PROTOCOL).toString();
String domain = optionService.getByPropertyOfNonNull(UpOssProperties.OSS_DOMAIN).toString();
String operator = optionService.getByPropertyOfNonNull(UpOssProperties.OSS_OPERATOR).toString();
// style rule can be null
String styleRule = optionService.getByPropertyOrDefault(UpOssProperties.OSS_STYLE_RULE, String.class, "");
String thumbnailStyleRule = optionService.getByPropertyOrDefault(UpOssProperties.OSS_THUMBNAIL_STYLE_RULE, String.class, "");
RestManager manager = new RestManager(bucket, operator, password);
manager.setTimeout(60 * 10);
manager.setApiDomain(RestManager.ED_AUTO);
Map<String, String> params = new HashMap<>();
try {
// Get file basename
String basename = FilenameUtils.getBasename(Objects.requireNonNull(file.getOriginalFilename()));
// Get file extension
String extension = FilenameUtils.getExtension(file.getOriginalFilename());
// Get md5 value of the file
String md5OfFile = DigestUtils.md5DigestAsHex(file.getInputStream());
// Build file path
String upFilePath = StringUtils.appendIfMissing(source, "/") + md5OfFile + '.' + extension;
// Set md5Content
params.put(RestManager.PARAMS.CONTENT_MD5.getValue(), md5OfFile);
// Write file
Response result = manager.writeFile(upFilePath, file.getInputStream(), params);
if (!result.isSuccessful()) {
throw new FileOperationException("上传附件 " + file.getOriginalFilename() + " 到又拍云失败" + upFilePath);
}
String filePath = protocol + StringUtils.removeEnd(domain, "/") + upFilePath;
// Build upload result
UploadResult uploadResult = new UploadResult();
uploadResult.setFilename(basename);
uploadResult.setFilePath(StringUtils.isBlank(styleRule) ? filePath : filePath + styleRule);
uploadResult.setKey(upFilePath);
uploadResult.setMediaType(MediaType.valueOf(Objects.requireNonNull(file.getContentType())));
uploadResult.setSuffix(extension);
uploadResult.setSize(file.getSize());
// Handle thumbnail
handleImageMetadata(file, uploadResult, () -> {
if (ImageUtils.EXTENSION_ICO.equals(extension)) {
uploadResult.setThumbPath(filePath);
return filePath;
} else {
return StringUtils.isBlank(thumbnailStyleRule) ? filePath : filePath + thumbnailStyleRule;
}
});
result.close();
return uploadResult;
} catch (Exception e) {
throw new FileOperationException("上传附件 " + file.getOriginalFilename() + " 到又拍云失败", e);
}
}
use of run.halo.app.model.support.UploadResult in project halo by halo-dev.
the class BaiduBosFileHandler method upload.
@Override
public UploadResult upload(MultipartFile file) {
Assert.notNull(file, "Multipart file must not be null");
// Get config
Object protocol = optionService.getByPropertyOfNonNull(BaiduBosProperties.BOS_PROTOCOL);
String domain = optionService.getByPropertyOrDefault(BaiduBosProperties.BOS_DOMAIN, String.class, "");
String endPoint = optionService.getByPropertyOfNonNull(BaiduBosProperties.BOS_ENDPOINT).toString();
String accessKey = optionService.getByPropertyOfNonNull(BaiduBosProperties.BOS_ACCESS_KEY).toString();
String secretKey = optionService.getByPropertyOfNonNull(BaiduBosProperties.BOS_SECRET_KEY).toString();
String bucketName = optionService.getByPropertyOfNonNull(BaiduBosProperties.BOS_BUCKET_NAME).toString();
String styleRule = optionService.getByPropertyOrDefault(BaiduBosProperties.BOS_STYLE_RULE, String.class, "");
String thumbnailStyleRule = optionService.getByPropertyOrDefault(BaiduBosProperties.BOS_THUMBNAIL_STYLE_RULE, String.class, "");
String source = StringUtils.join(protocol, bucketName, "." + endPoint);
BosClientConfiguration config = new BosClientConfiguration();
config.setCredentials(new DefaultBceCredentials(accessKey, secretKey));
config.setEndpoint(endPoint);
// Init OSS client
BosClient client = new BosClient(config);
domain = protocol + domain;
try {
FilePathDescriptor pathDescriptor = new FilePathDescriptor.Builder().setBasePath(domain).setSubPath(source).setAutomaticRename(true).setRenamePredicate(relativePath -> attachmentRepository.countByFileKeyAndType(relativePath, AttachmentType.BAIDUBOS) > 0).setOriginalName(file.getOriginalFilename()).build();
// Upload
PutObjectResponse putObjectResponseFromInputStream = client.putObject(bucketName, pathDescriptor.getFullName(), file.getInputStream());
if (putObjectResponseFromInputStream == null) {
throw new FileOperationException("上传附件 " + file.getOriginalFilename() + " 到百度云失败 ");
}
// Response result
UploadResult uploadResult = new UploadResult();
uploadResult.setFilename(pathDescriptor.getFullName());
String fullPath = pathDescriptor.getFullPath();
uploadResult.setFilePath(StringUtils.isBlank(styleRule) ? fullPath : fullPath + styleRule);
uploadResult.setKey(pathDescriptor.getRelativePath());
uploadResult.setMediaType(MediaType.valueOf(Objects.requireNonNull(file.getContentType())));
uploadResult.setSuffix(pathDescriptor.getExtension());
uploadResult.setSize(file.getSize());
// Handle thumbnail
handleImageMetadata(file, uploadResult, () -> {
if (ImageUtils.EXTENSION_ICO.equals(pathDescriptor.getExtension())) {
return fullPath;
} else {
return StringUtils.isBlank(thumbnailStyleRule) ? fullPath : fullPath + thumbnailStyleRule;
}
});
return uploadResult;
} catch (Exception e) {
throw new FileOperationException("附件 " + file.getOriginalFilename() + " 上传失败(百度云)", e);
} finally {
client.shutdown();
}
}
use of run.halo.app.model.support.UploadResult in project halo by halo-dev.
the class LocalFileHandler method upload.
@NonNull
@Override
public UploadResult upload(@NonNull MultipartFile file) {
Assert.notNull(file, "Multipart file must not be null");
FilePathDescriptor uploadFilePath = new FilePathDescriptor.Builder().setBasePath(workDir).setSubPath(generatePath()).setSeparator(FILE_SEPARATOR).setAutomaticRename(true).setRenamePredicate(relativePath -> attachmentRepository.countByFileKeyAndType(relativePath, AttachmentType.LOCAL) > 0).setOriginalName(file.getOriginalFilename()).build();
log.info("Uploading file: [{}] to directory: [{}]", file.getOriginalFilename(), uploadFilePath.getRelativePath());
Path localFileFullPath = Paths.get(uploadFilePath.getFullPath());
try {
// TODO Synchronize here
// Create directory
Files.createDirectories(localFileFullPath.getParent());
Files.createFile(localFileFullPath);
// Upload this file
file.transferTo(localFileFullPath);
// Build upload result
UploadResult uploadResult = new UploadResult();
uploadResult.setFilename(uploadFilePath.getName());
uploadResult.setFilePath(uploadFilePath.getRelativePath());
uploadResult.setKey(uploadFilePath.getRelativePath());
uploadResult.setSuffix(uploadFilePath.getExtension());
uploadResult.setMediaType(MediaType.valueOf(Objects.requireNonNull(file.getContentType())));
uploadResult.setSize(file.getSize());
// TODO refactor this: if image is svg ext. extension
handleImageMetadata(file, uploadResult, () -> {
// Upload a thumbnail
FilePathDescriptor thumbnailFilePath = new FilePathDescriptor.Builder().setBasePath(workDir).setSubPath(uploadFilePath.getSubPath()).setSeparator(FILE_SEPARATOR).setOriginalName(uploadFilePath.getFullName()).setNameSuffix(THUMBNAIL_SUFFIX).build();
final Path thumbnailPath = Paths.get(thumbnailFilePath.getFullPath());
try (InputStream is = file.getInputStream()) {
// Generate thumbnail
BufferedImage originalImage = ImageUtils.getImageFromFile(is, uploadFilePath.getExtension());
boolean result = generateThumbnail(originalImage, thumbnailPath, uploadFilePath.getExtension());
if (result) {
// Set thumb path
return thumbnailFilePath.getRelativePath();
}
} catch (Throwable e) {
log.warn("Failed to open image file.", e);
}
return uploadFilePath.getRelativePath();
});
log.info("Uploaded file: [{}] to directory: [{}] successfully", file.getOriginalFilename(), uploadFilePath.getFullPath());
return uploadResult;
} catch (IOException e) {
throw new FileOperationException("上传附件失败").setErrorData(uploadFilePath.getFullPath());
}
}
Aggregations