Search in sources :

Example 6 with UploadResult

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

the class AttachmentServiceImpl method upload.

@Override
public Attachment upload(MultipartFile file) {
    Assert.notNull(file, "Multipart file must not be null");
    AttachmentType attachmentType = getAttachmentType();
    log.debug("Starting uploading... type: [{}], file: [{}]", attachmentType, file.getOriginalFilename());
    // Upload file
    UploadResult uploadResult = fileHandlers.upload(file, attachmentType);
    log.debug("Attachment type: [{}]", attachmentType);
    log.debug("Upload result: [{}]", uploadResult);
    // Build attachment
    Attachment attachment = new Attachment();
    attachment.setName(uploadResult.getFilename());
    // Convert separator
    attachment.setPath(HaloUtils.changeFileSeparatorToUrlSeparator(uploadResult.getFilePath()));
    attachment.setFileKey(uploadResult.getKey());
    attachment.setThumbPath(uploadResult.getThumbPath());
    attachment.setMediaType(uploadResult.getMediaType().toString());
    attachment.setSuffix(uploadResult.getSuffix());
    attachment.setWidth(uploadResult.getWidth());
    attachment.setHeight(uploadResult.getHeight());
    attachment.setSize(uploadResult.getSize());
    attachment.setType(attachmentType);
    log.debug("Creating attachment: [{}]", attachment);
    // Create and return
    return create(attachment);
}
Also used : AttachmentType(run.halo.app.model.enums.AttachmentType) Attachment(run.halo.app.model.entity.Attachment) UploadResult(run.halo.app.model.support.UploadResult)

Example 7 with UploadResult

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

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 8 with UploadResult

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

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 9 with UploadResult

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

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();
    }
}
Also used : COSCredentials(com.qcloud.cos.auth.COSCredentials) BasicCOSCredentials(com.qcloud.cos.auth.BasicCOSCredentials) BasicCOSCredentials(com.qcloud.cos.auth.BasicCOSCredentials) PutObjectResult(com.qcloud.cos.model.PutObjectResult) FileOperationException(run.halo.app.exception.FileOperationException) FileOperationException(run.halo.app.exception.FileOperationException) COSClient(com.qcloud.cos.COSClient) Region(com.qcloud.cos.region.Region) UploadResult(run.halo.app.model.support.UploadResult) ClientConfig(com.qcloud.cos.ClientConfig) ObjectMetadata(com.qcloud.cos.model.ObjectMetadata)

Example 10 with UploadResult

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

the class QiniuOssFileHandler method upload.

@Override
public UploadResult upload(MultipartFile file) {
    Assert.notNull(file, "Multipart file must not be null");
    Region region = optionService.getQiniuRegion();
    String accessKey = optionService.getByPropertyOfNonNull(QiniuOssProperties.OSS_ACCESS_KEY).toString();
    String secretKey = optionService.getByPropertyOfNonNull(QiniuOssProperties.OSS_SECRET_KEY).toString();
    String bucket = optionService.getByPropertyOfNonNull(QiniuOssProperties.OSS_BUCKET).toString();
    String protocol = optionService.getByPropertyOfNonNull(QiniuOssProperties.OSS_PROTOCOL).toString();
    String domain = optionService.getByPropertyOfNonNull(QiniuOssProperties.OSS_DOMAIN).toString();
    String source = optionService.getByPropertyOrDefault(QiniuOssProperties.OSS_SOURCE, String.class, "");
    String styleRule = optionService.getByPropertyOrDefault(QiniuOssProperties.OSS_STYLE_RULE, String.class, "");
    String thumbnailStyleRule = optionService.getByPropertyOrDefault(QiniuOssProperties.OSS_THUMBNAIL_STYLE_RULE, String.class, "");
    // Create configuration
    Configuration configuration = new Configuration(region);
    // Create auth
    Auth auth = Auth.create(accessKey, secretKey);
    // Build put plicy
    StringMap putPolicy = new StringMap();
    putPolicy.put("returnBody", "{\"key\":\"$(key)\",\"hash\":\"$(etag)\",\"size\":$(fsize),\"width\":$(imageInfo" + ".width),\"height\":$(imageInfo.height)}");
    // Get upload token
    String uploadToken = auth.uploadToken(bucket, null, 60 * 60, putPolicy);
    // Create temp path
    Path tmpPath = Paths.get(ensureSuffix(TEMP_DIR, FILE_SEPARATOR), bucket);
    StringBuilder basePath = new StringBuilder(protocol).append(domain).append(URL_SEPARATOR);
    try {
        FilePathDescriptor pathDescriptor = new FilePathDescriptor.Builder().setBasePath(basePath.toString()).setSubPath(source).setAutomaticRename(true).setRenamePredicate(relativePath -> attachmentRepository.countByFileKeyAndType(relativePath, AttachmentType.QINIUOSS) > 0).setOriginalName(file.getOriginalFilename()).build();
        // Get file recorder for temp directory
        FileRecorder fileRecorder = new FileRecorder(tmpPath.toFile());
        // Get upload manager
        UploadManager uploadManager = new UploadManager(configuration, fileRecorder);
        // Put the file
        Response response = uploadManager.put(file.getInputStream(), pathDescriptor.getRelativePath(), uploadToken, null, null);
        if (log.isDebugEnabled()) {
            log.debug("Qiniu oss response: [{}]", response.toString());
            log.debug("Qiniu oss response body: [{}]", response.bodyString());
        }
        // Convert response
        PutSet putSet = JsonUtils.jsonToObject(response.bodyString(), PutSet.class);
        // Get file full path
        String fullPath = pathDescriptor.getFullPath();
        // Build upload result
        UploadResult result = new UploadResult();
        result.setFilename(pathDescriptor.getName());
        result.setFilePath(StringUtils.isBlank(styleRule) ? fullPath : fullPath + styleRule);
        result.setKey(pathDescriptor.getRelativePath());
        result.setSuffix(pathDescriptor.getExtension());
        result.setWidth(putSet.getWidth());
        result.setHeight(putSet.getHeight());
        result.setMediaType(MediaType.valueOf(Objects.requireNonNull(file.getContentType())));
        result.setSize(file.getSize());
        if (isImageType(file)) {
            if (ImageUtils.EXTENSION_ICO.equals(pathDescriptor.getExtension())) {
                result.setThumbPath(fullPath);
            } else {
                result.setThumbPath(StringUtils.isBlank(thumbnailStyleRule) ? fullPath : fullPath + thumbnailStyleRule);
            }
        }
        return result;
    } catch (IOException e) {
        if (e instanceof QiniuException) {
            log.error("Qiniu oss error response: [{}]", ((QiniuException) e).response);
        }
        throw new FileOperationException("上传附件 " + file.getOriginalFilename() + " 到七牛云失败", e);
    }
}
Also used : Path(java.nio.file.Path) StringMap(com.qiniu.util.StringMap) Configuration(com.qiniu.storage.Configuration) FileOperationException(run.halo.app.exception.FileOperationException) FileRecorder(com.qiniu.storage.persistent.FileRecorder) IOException(java.io.IOException) Response(com.qiniu.http.Response) QiniuException(com.qiniu.common.QiniuException) Auth(com.qiniu.util.Auth) Region(com.qiniu.storage.Region) UploadResult(run.halo.app.model.support.UploadResult) UploadManager(com.qiniu.storage.UploadManager)

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