原创

java上传文件到OSS云服务器(二)

`上篇文章中已经把接口端和service业务层写了,这次就把OSS上传文件的工具类补上。 一、首先配置好OSS服务器各项节点,这是在springboot中appliaction.yml配置文件中的写法。

@Component
public class OssConstant implements InitializingBean {

@Value("${oss.file.endpoint_im}")
private String oss_file_endpointim;

@Value("${oss.file.bucket_im}")
private String oss_file_bucketim;

@Value("${oss.file.keyid_im}")
private String oss_file_keyid_im;

@Value("${oss.file.keysecret_im}")
private String oss_file_keysecret_im;

@Value("${oss.file.bucketprefix}")
private String oss_file_bucketprefix;

public static String OSS_END_POINT_IM ;
public static String OSS_BUCKET_IM ; ;
public static String OSS_ACCESS_KEY_ID_IM ;
public static String OSS_ACCESS_KEY_SECRET_IM ;
public static String OSS_FILE_BUCKETPREFIX ;

@Override
public void afterPropertiesSet() throws Exception {
OSS_END_POINT_IM = oss_file_endpointim;
OSS_BUCKET_IM = oss_file_bucketim;
OSS_ACCESS_KEY_ID_IM = oss_file_keyid_im;
OSS_ACCESS_KEY_SECRET_IM = oss_file_keysecret_im;
OSS_FILE_BUCKETPREFIX = oss_file_bucketprefix;
}
}

二、OSS上传工具类

public class AliyunOSSUtil {
private static final String accessKeyId_im=OssConstant.OSS_ACCESS_KEY_ID_IM;
private static final String accessKeySecret_im=OssConstant.OSS_ACCESS_KEY_SECRET_IM;
private static final String endpoint_im = OssConstant.OSS_END_POINT_IM;
private static final String bucket_im = OssConstant.OSS_BUCKET_IM;

public static String OSSUploadFile(File file){
SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
String dateStr = format.format(new Date());
if(null == file){
return null;
}
OSSClient ossClient = new OSSClient(endpoint_im,accessKeyId_im,accessKeySecret_im);
try {
//容器不存在,就创建
if(! ossClient.doesBucketExist(bucket_im)){
ossClient.createBucket(bucket_im);
CreateBucketRequest createBucketRequest = new CreateBucketRequest(bucket_im);
createBucketRequest.setCannedACL(CannedAccessControlList.Default);
ossClient.createBucket(createBucketRequest);
}

    String fileUrl = dateStr + "/" + new Date().getTime()+"-"+file.getName();

    //上传文件
    PutObjectResult result = ossClient.putObject(new PutObjectRequest(bucket_im, fileUrl, file));
    //设置权限 这里是私有权限读写
   ossClient.setBucketAcl(bucketName,CannedAccessControlList.Default);
    if(null != result){
        logger.info("==========>OSS文件上传成功,OSS地址:"+fileUrl);
        return fileBucketprefix+"/"+fileUrl;
    }
}catch (OSSException oe){
    logger.error(oe.getMessage());
}catch (ClientException ce){
    logger.error(ce.getMessage());
}finally {
    //关闭
    ossClient.shutdown();
}
return null;

}
}
至此,文件已经成功上传到OSS云服务器了。

正文到此结束
该篇文章的评论功能已被站长关闭
本文目录