Search in sources :

Example 56 with PutObjectResult

use of com.aliyun.oss.model.PutObjectResult in project jeecg-boot by jeecgboot.

the class OssBootUtil method upload.

/**
 * 上传文件到oss
 * @param stream
 * @param relativePath
 * @return
 */
public static String upload(InputStream stream, String relativePath) {
    String FILE_URL = null;
    String fileUrl = relativePath;
    initOSS(endPoint, accessKeyId, accessKeySecret);
    if (oConvertUtils.isNotEmpty(staticDomain) && staticDomain.toLowerCase().startsWith("http")) {
        FILE_URL = staticDomain + "/" + relativePath;
    } else {
        FILE_URL = "https://" + bucketName + "." + endPoint + "/" + fileUrl;
    }
    PutObjectResult result = ossClient.putObject(bucketName, fileUrl.toString(), stream);
    // 设置权限(公开读)
    ossClient.setBucketAcl(bucketName, CannedAccessControlList.PublicRead);
    if (result != null) {
        log.info("------OSS文件上传成功------" + fileUrl);
    }
    return FILE_URL;
}
Also used : PutObjectResult(com.aliyun.oss.model.PutObjectResult)

Example 57 with PutObjectResult

use of com.aliyun.oss.model.PutObjectResult in project jeecg-boot by jeecgboot.

the class OssBootUtil method upload.

/**
 * 上传文件至阿里云 OSS
 * 文件上传成功,返回文件完整访问路径
 * 文件上传失败,返回 null
 *
 * @param file    待上传文件
 * @param fileDir 文件保存目录
 * @return oss 中的相对文件路径
 */
public static String upload(MultipartFile file, String fileDir, String customBucket) {
    String FILE_URL = null;
    initOSS(endPoint, accessKeyId, accessKeySecret);
    StringBuilder fileUrl = new StringBuilder();
    String newBucket = bucketName;
    if (oConvertUtils.isNotEmpty(customBucket)) {
        newBucket = customBucket;
    }
    try {
        // 判断桶是否存在,不存在则创建桶
        if (!ossClient.doesBucketExist(newBucket)) {
            ossClient.createBucket(newBucket);
        }
        // 获取文件名
        String orgName = file.getOriginalFilename();
        if ("" == orgName) {
            orgName = file.getName();
        }
        // update-begin-author:liusq date:20210809 for: 过滤上传文件类型
        FileTypeFilter.fileTypeFilter(file);
        // update-end-author:liusq date:20210809 for: 过滤上传文件类型
        orgName = CommonUtils.getFileName(orgName);
        String fileName = orgName.indexOf(".") == -1 ? orgName + "_" + System.currentTimeMillis() : orgName.substring(0, orgName.lastIndexOf(".")) + "_" + System.currentTimeMillis() + orgName.substring(orgName.lastIndexOf("."));
        if (!fileDir.endsWith("/")) {
            fileDir = fileDir.concat("/");
        }
        // update-begin-author:wangshuai date:20201012 for: 过滤上传文件夹名特殊字符,防止攻击
        fileDir = StrAttackFilter.filter(fileDir);
        // update-end-author:wangshuai date:20201012 for: 过滤上传文件夹名特殊字符,防止攻击
        fileUrl = fileUrl.append(fileDir + fileName);
        if (oConvertUtils.isNotEmpty(staticDomain) && staticDomain.toLowerCase().startsWith("http")) {
            FILE_URL = staticDomain + "/" + fileUrl;
        } else {
            FILE_URL = "https://" + newBucket + "." + endPoint + "/" + fileUrl;
        }
        PutObjectResult result = ossClient.putObject(newBucket, fileUrl.toString(), file.getInputStream());
        // ossClient.setBucketAcl(newBucket, CannedAccessControlList.PublicRead);
        if (result != null) {
            log.info("------OSS文件上传成功------" + fileUrl);
        }
    } catch (IOException e) {
        e.printStackTrace();
        return null;
    } catch (Exception e) {
        e.printStackTrace();
        return null;
    }
    return FILE_URL;
}
Also used : PutObjectResult(com.aliyun.oss.model.PutObjectResult) IOException(java.io.IOException) IOException(java.io.IOException)

Example 58 with PutObjectResult

use of com.aliyun.oss.model.PutObjectResult in project jeecg-boot by jeecgboot.

the class OssBootUtil method upload.

/**
 * 上传文件至阿里云 OSS
 * 文件上传成功,返回文件完整访问路径
 * 文件上传失败,返回 null
 *
 * @param file    待上传文件
 * @param fileDir 文件保存目录
 * @return oss 中的相对文件路径
 */
public static String upload(FileItemStream file, String fileDir) {
    String FILE_URL = null;
    initOSS(endPoint, accessKeyId, accessKeySecret);
    StringBuilder fileUrl = new StringBuilder();
    try {
        String suffix = file.getName().substring(file.getName().lastIndexOf('.'));
        String fileName = UUID.randomUUID().toString().replace("-", "") + suffix;
        if (!fileDir.endsWith("/")) {
            fileDir = fileDir.concat("/");
        }
        fileDir = StrAttackFilter.filter(fileDir);
        fileUrl = fileUrl.append(fileDir + fileName);
        if (oConvertUtils.isNotEmpty(staticDomain) && staticDomain.toLowerCase().startsWith("http")) {
            FILE_URL = staticDomain + "/" + fileUrl;
        } else {
            FILE_URL = "https://" + bucketName + "." + endPoint + "/" + fileUrl;
        }
        PutObjectResult result = ossClient.putObject(bucketName, fileUrl.toString(), file.openStream());
        // 设置权限(公开读)
        ossClient.setBucketAcl(bucketName, CannedAccessControlList.PublicRead);
        if (result != null) {
            log.info("------OSS文件上传成功------" + fileUrl);
        }
    } catch (IOException e) {
        e.printStackTrace();
        return null;
    }
    return FILE_URL;
}
Also used : PutObjectResult(com.aliyun.oss.model.PutObjectResult) IOException(java.io.IOException)

Example 59 with PutObjectResult

use of com.aliyun.oss.model.PutObjectResult in project kms by mahonelau.

the class OssBootUtil method upload.

/**
 * 上传文件至阿里云 OSS
 * 文件上传成功,返回文件完整访问路径
 * 文件上传失败,返回 null
 *
 * @param file    待上传文件
 * @param fileDir 文件保存目录
 * @return oss 中的相对文件路径
 */
public static String upload(FileItemStream file, String fileDir) {
    String FILE_URL = null;
    initOSS(endPoint, accessKeyId, accessKeySecret);
    StringBuilder fileUrl = new StringBuilder();
    try {
        String suffix = file.getName().substring(file.getName().lastIndexOf('.'));
        String fileName = UUID.randomUUID().toString().replace("-", "") + suffix;
        if (!fileDir.endsWith("/")) {
            fileDir = fileDir.concat("/");
        }
        fileDir = StrAttackFilter.filter(fileDir);
        fileUrl = fileUrl.append(fileDir + fileName);
        if (oConvertUtils.isNotEmpty(staticDomain) && staticDomain.toLowerCase().startsWith("http")) {
            FILE_URL = staticDomain + "/" + fileUrl;
        } else {
            FILE_URL = "https://" + bucketName + "." + endPoint + "/" + fileUrl;
        }
        PutObjectResult result = ossClient.putObject(bucketName, fileUrl.toString(), file.openStream());
        // 设置权限(公开读)
        ossClient.setBucketAcl(bucketName, CannedAccessControlList.PublicRead);
        if (result != null) {
            log.info("------OSS文件上传成功------" + fileUrl);
        }
    } catch (IOException e) {
        e.printStackTrace();
        return null;
    }
    return FILE_URL;
}
Also used : PutObjectResult(com.aliyun.oss.model.PutObjectResult) IOException(java.io.IOException)

Example 60 with PutObjectResult

use of com.aliyun.oss.model.PutObjectResult in project halo by halo-dev.

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)

Aggregations

PutObjectResult (com.aliyun.oss.model.PutObjectResult)60 Test (org.junit.Test)31 OSSException (com.aliyun.oss.OSSException)30 InputStream (java.io.InputStream)24 OSSObject (com.aliyun.oss.model.OSSObject)20 ObjectMetadata (com.aliyun.oss.model.ObjectMetadata)19 File (java.io.File)15 PutObjectRequest (com.aliyun.oss.model.PutObjectRequest)13 TestUtils.genFixedLengthInputStream (com.aliyun.oss.integrationtests.TestUtils.genFixedLengthInputStream)10 ByteArrayInputStream (java.io.ByteArrayInputStream)10 ArrayList (java.util.ArrayList)10 FileInputStream (java.io.FileInputStream)9 Callback (com.aliyun.oss.model.Callback)8 IOException (java.io.IOException)8 GetObjectRequest (com.aliyun.oss.model.GetObjectRequest)7 Date (java.util.Date)7 OSS (com.aliyun.oss.OSS)6 CopyObjectResult (com.aliyun.oss.model.CopyObjectResult)6 Ignore (org.junit.Ignore)6 CompleteMultipartUploadRequest (com.aliyun.oss.model.CompleteMultipartUploadRequest)5