Search in sources :

Example 1 with UploadResult

use of run.halo.app.model.support.UploadResult in project halo by ruibaby.

the class AliOssFileHandler method upload.

@Override
@NonNull
public UploadResult upload(@NonNull MultipartFile file) {
    Assert.notNull(file, "Multipart file must not be null");
    // Get config
    String protocol = optionService.getByPropertyOfNonNull(AliOssProperties.OSS_PROTOCOL).toString();
    String domain = optionService.getByPropertyOrDefault(AliOssProperties.OSS_DOMAIN, String.class, "");
    String source = optionService.getByPropertyOrDefault(AliOssProperties.OSS_SOURCE, String.class, "");
    String endPoint = optionService.getByPropertyOfNonNull(AliOssProperties.OSS_ENDPOINT).toString();
    String accessKey = optionService.getByPropertyOfNonNull(AliOssProperties.OSS_ACCESS_KEY).toString();
    String accessSecret = optionService.getByPropertyOfNonNull(AliOssProperties.OSS_ACCESS_SECRET).toString();
    String bucketName = optionService.getByPropertyOfNonNull(AliOssProperties.OSS_BUCKET_NAME).toString();
    String styleRule = optionService.getByPropertyOrDefault(AliOssProperties.OSS_STYLE_RULE, String.class, "");
    String thumbnailStyleRule = optionService.getByPropertyOrDefault(AliOssProperties.OSS_THUMBNAIL_STYLE_RULE, String.class, "");
    // Init OSS client
    OSS ossClient = new OSSClientBuilder().build(endPoint, accessKey, accessSecret);
    StringBuilder basePath = new StringBuilder(protocol);
    if (StringUtils.isNotEmpty(domain)) {
        basePath.append(domain).append(URL_SEPARATOR);
    } else {
        basePath.append(bucketName).append(".").append(endPoint).append(URL_SEPARATOR);
    }
    try {
        FilePathDescriptor uploadFilePath = new FilePathDescriptor.Builder().setBasePath(basePath.toString()).setSubPath(source).setAutomaticRename(true).setRenamePredicate(relativePath -> attachmentRepository.countByFileKeyAndType(relativePath, AttachmentType.ALIOSS) > 0).setOriginalName(file.getOriginalFilename()).build();
        log.info(basePath.toString());
        // Upload
        final PutObjectResult putObjectResult = ossClient.putObject(bucketName, uploadFilePath.getRelativePath(), file.getInputStream());
        if (putObjectResult == null) {
            throw new FileOperationException("上传附件 " + file.getOriginalFilename() + " 到阿里云失败 ");
        }
        // Response result
        final UploadResult uploadResult = new UploadResult();
        uploadResult.setFilename(uploadFilePath.getName());
        String fullPath = uploadFilePath.getFullPath();
        uploadResult.setFilePath(StringUtils.isBlank(styleRule) ? fullPath : fullPath + styleRule);
        uploadResult.setKey(uploadFilePath.getRelativePath());
        uploadResult.setMediaType(MediaType.valueOf(Objects.requireNonNull(file.getContentType())));
        uploadResult.setSuffix(uploadFilePath.getExtension());
        uploadResult.setSize(file.getSize());
        handleImageMetadata(file, uploadResult, () -> {
            if (ImageUtils.EXTENSION_ICO.equals(uploadFilePath.getExtension())) {
                return fullPath;
            } else {
                return StringUtils.isBlank(thumbnailStyleRule) ? fullPath : fullPath + thumbnailStyleRule;
            }
        });
        log.info("Uploaded file: [{}] successfully", file.getOriginalFilename());
        return uploadResult;
    } catch (Exception e) {
        throw new FileOperationException("上传附件 " + file.getOriginalFilename() + " 到阿里云失败 ", e).setErrorData(file.getOriginalFilename());
    } finally {
        ossClient.shutdown();
    }
}
Also used : PutObjectResult(com.aliyun.oss.model.PutObjectResult) OSSClientBuilder(com.aliyun.oss.OSSClientBuilder) FileOperationException(run.halo.app.exception.FileOperationException) UploadResult(run.halo.app.model.support.UploadResult) OSS(com.aliyun.oss.OSS) OSSClientBuilder(com.aliyun.oss.OSSClientBuilder) FileOperationException(run.halo.app.exception.FileOperationException) NonNull(org.springframework.lang.NonNull)

Example 2 with UploadResult

use of run.halo.app.model.support.UploadResult in project halo by ruibaby.

the class HuaweiObsFileHandler method upload.

@Override
@NonNull
public UploadResult upload(@NonNull MultipartFile file) {
    Assert.notNull(file, "Multipart file must not be null");
    // Get config
    String protocol = optionService.getByPropertyOfNonNull(HuaweiObsProperties.OSS_PROTOCOL).toString();
    String domain = optionService.getByPropertyOrDefault(HuaweiObsProperties.OSS_DOMAIN, String.class, "");
    String source = optionService.getByPropertyOrDefault(HuaweiObsProperties.OSS_SOURCE, String.class, "");
    String endPoint = optionService.getByPropertyOfNonNull(HuaweiObsProperties.OSS_ENDPOINT).toString();
    String accessKey = optionService.getByPropertyOfNonNull(HuaweiObsProperties.OSS_ACCESS_KEY).toString();
    String accessSecret = optionService.getByPropertyOfNonNull(HuaweiObsProperties.OSS_ACCESS_SECRET).toString();
    String bucketName = optionService.getByPropertyOfNonNull(HuaweiObsProperties.OSS_BUCKET_NAME).toString();
    String styleRule = optionService.getByPropertyOrDefault(HuaweiObsProperties.OSS_STYLE_RULE, String.class, "");
    String thumbnailStyleRule = optionService.getByPropertyOrDefault(HuaweiObsProperties.OSS_THUMBNAIL_STYLE_RULE, String.class, "");
    // Init OSS client
    final ObsClient obsClient = new ObsClient(accessKey, accessSecret, endPoint);
    StringBuilder basePath = new StringBuilder(protocol);
    if (StringUtils.isNotEmpty(domain)) {
        basePath.append(domain).append(URL_SEPARATOR);
    } else {
        basePath.append(bucketName).append(".").append(endPoint).append(URL_SEPARATOR);
    }
    try {
        FilePathDescriptor pathDescriptor = new FilePathDescriptor.Builder().setBasePath(basePath.toString()).setSubPath(source).setAutomaticRename(true).setRenamePredicate(relativePath -> attachmentRepository.countByFileKeyAndType(relativePath, AttachmentType.HUAWEIOBS) > 0).setOriginalName(file.getOriginalFilename()).build();
        log.info(basePath.toString());
        // Upload
        PutObjectResult putObjectResult = obsClient.putObject(bucketName, pathDescriptor.getRelativePath(), file.getInputStream());
        if (putObjectResult == null) {
            throw new FileOperationException("上传附件 " + file.getOriginalFilename() + " 到华为云失败 ");
        }
        // Response result
        UploadResult uploadResult = new UploadResult();
        uploadResult.setFilename(pathDescriptor.getName());
        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());
        handleImageMetadata(file, uploadResult, () -> {
            if (ImageUtils.EXTENSION_ICO.equals(pathDescriptor.getExtension())) {
                return fullPath;
            } else {
                return StringUtils.isBlank(thumbnailStyleRule) ? fullPath : fullPath + thumbnailStyleRule;
            }
        });
        log.info("Uploaded file: [{}] successfully", file.getOriginalFilename());
        return uploadResult;
    } catch (Exception e) {
        throw new FileOperationException("上传附件 " + file.getOriginalFilename() + " 到华为云失败 ", e).setErrorData(file.getOriginalFilename());
    } finally {
        try {
            obsClient.close();
        } catch (IOException e) {
            log.error(e.getMessage());
        }
    }
}
Also used : PutObjectResult(com.obs.services.model.PutObjectResult) FileOperationException(run.halo.app.exception.FileOperationException) UploadResult(run.halo.app.model.support.UploadResult) IOException(java.io.IOException) ObsClient(com.obs.services.ObsClient) FileOperationException(run.halo.app.exception.FileOperationException) IOException(java.io.IOException) NonNull(org.springframework.lang.NonNull)

Example 3 with UploadResult

use of run.halo.app.model.support.UploadResult in project halo by ruibaby.

the class SmmsFileHandler method upload.

@Override
public UploadResult upload(MultipartFile file) {
    Assert.notNull(file, "Multipart file must not be null");
    String apiSecretToken = optionService.getByPropertyOfNonNull(SmmsProperties.SMMS_API_SECRET_TOKEN).toString();
    if (StringUtils.isEmpty(apiSecretToken)) {
        throw new ServiceException("请先设置 SM.MS 的 Secret Token");
    }
    if (!isImageType(file)) {
        log.error("Invalid extension: [{}]", file.getContentType());
        throw new FileOperationException("不支持的文件类型,仅支持 \"jpeg, jpg, png, gif, bmp\" 格式的图片");
    }
    setHeaders();
    // Set content type
    headers.setContentType(MediaType.MULTIPART_FORM_DATA);
    LinkedMultiValueMap<String, Object> body = new LinkedMultiValueMap<>();
    try {
        body.add("smfile", new HttpClientUtils.MultipartFileResource(file.getBytes(), file.getOriginalFilename()));
    } catch (IOException e) {
        log.error("Failed to get file input stream", e);
        throw new FileOperationException("上传附件 " + file.getOriginalFilename() + " 到 SM.MS 失败", e);
    }
    body.add("format", "json");
    HttpEntity<LinkedMultiValueMap<String, Object>> httpEntity = new HttpEntity<>(body, headers);
    // Upload file
    ResponseEntity<SmmsResponse> mapResponseEntity = httpsRestTemplate.postForEntity(UPLOAD_API_V2, httpEntity, SmmsResponse.class);
    // Check status
    if (mapResponseEntity.getStatusCode().isError()) {
        log.error("Server response detail: [{}]", mapResponseEntity);
        throw new FileOperationException("SM.MS 服务状态异常,状态码: " + mapResponseEntity.getStatusCodeValue());
    }
    // Get smms response
    SmmsResponse smmsResponse = mapResponseEntity.getBody();
    // Check error
    if (!isResponseSuccessfully(smmsResponse)) {
        log.error("Smms response detail: [{}]", smmsResponse);
        throw new FileOperationException(smmsResponse == null ? "SM.MS 服务返回内容为空" : smmsResponse.getMessage()).setErrorData(smmsResponse);
    }
    if (!smmsResponse.getSuccess()) {
        throw new FileOperationException("上传请求失败:" + smmsResponse.getMessage()).setErrorData(smmsResponse);
    }
    // Get response data
    SmmsResponseData data = smmsResponse.getData();
    // Build result
    UploadResult result = new UploadResult();
    result.setFilename(FilenameUtils.getBasename(Objects.requireNonNull(file.getOriginalFilename())));
    result.setSuffix(FilenameUtils.getExtension(file.getOriginalFilename()));
    result.setMediaType(MediaType.valueOf(Objects.requireNonNull(file.getContentType())));
    result.setFilePath(data.getUrl());
    result.setThumbPath(data.getUrl());
    result.setKey(data.getHash());
    result.setWidth(data.getWidth());
    result.setHeight(data.getHeight());
    result.setSize(data.getSize().longValue());
    log.info("File: [{}] uploaded successfully", file.getOriginalFilename());
    return result;
}
Also used : HttpEntity(org.springframework.http.HttpEntity) LinkedMultiValueMap(org.springframework.util.LinkedMultiValueMap) FileOperationException(run.halo.app.exception.FileOperationException) IOException(java.io.IOException) HttpClientUtils(run.halo.app.utils.HttpClientUtils) ServiceException(run.halo.app.exception.ServiceException) UploadResult(run.halo.app.model.support.UploadResult)

Example 4 with UploadResult

use of run.halo.app.model.support.UploadResult in project halo by ruibaby.

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());
    }
}
Also used : Path(java.nio.file.Path) InputStream(java.io.InputStream) FileOperationException(run.halo.app.exception.FileOperationException) UploadResult(run.halo.app.model.support.UploadResult) IOException(java.io.IOException) BufferedImage(java.awt.image.BufferedImage) NonNull(org.springframework.lang.NonNull)

Example 5 with UploadResult

use of run.halo.app.model.support.UploadResult in project halo by ruibaby.

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();
    }
}
Also used : BosClientConfiguration(com.baidubce.services.bos.BosClientConfiguration) DefaultBceCredentials(com.baidubce.auth.DefaultBceCredentials) PutObjectResponse(com.baidubce.services.bos.model.PutObjectResponse) FileOperationException(run.halo.app.exception.FileOperationException) BosClient(com.baidubce.services.bos.BosClient) UploadResult(run.halo.app.model.support.UploadResult) FileOperationException(run.halo.app.exception.FileOperationException)

Aggregations

UploadResult (run.halo.app.model.support.UploadResult)20 FileOperationException (run.halo.app.exception.FileOperationException)18 IOException (java.io.IOException)10 NonNull (org.springframework.lang.NonNull)8 Path (java.nio.file.Path)4 OSS (com.aliyun.oss.OSS)2 OSSClientBuilder (com.aliyun.oss.OSSClientBuilder)2 PutObjectResult (com.aliyun.oss.model.PutObjectResult)2 DefaultBceCredentials (com.baidubce.auth.DefaultBceCredentials)2 BosClient (com.baidubce.services.bos.BosClient)2 BosClientConfiguration (com.baidubce.services.bos.BosClientConfiguration)2 PutObjectResponse (com.baidubce.services.bos.model.PutObjectResponse)2 ObsClient (com.obs.services.ObsClient)2 PutObjectResult (com.obs.services.model.PutObjectResult)2 COSClient (com.qcloud.cos.COSClient)2 ClientConfig (com.qcloud.cos.ClientConfig)2 BasicCOSCredentials (com.qcloud.cos.auth.BasicCOSCredentials)2 COSCredentials (com.qcloud.cos.auth.COSCredentials)2 ObjectMetadata (com.qcloud.cos.model.ObjectMetadata)2 PutObjectResult (com.qcloud.cos.model.PutObjectResult)2