阿里云oss云存储

一 pom.xml配置

<!-- 阿里云相关 -->
            <dependency>
                <groupId>com.aliyun</groupId>
                <artifactId>aliyun-java-sdk-core</artifactId>
                <version>2.1.9</version>
            </dependency>
            <dependency>
                <groupId>com.aliyun.oss</groupId>
                <artifactId>aliyun-sdk-oss</artifactId>
                <version>2.0.5</version>
            </dependency>
            <dependency>
                <groupId>com.aliyun.opensearch</groupId>
                <artifactId>aliyun-sdk-opensearch</artifactId>
                <version>2.1.3</version>
            </dependency>
            <dependency>
                <groupId>com.aliyun</groupId>
                <artifactId>aliyun-java-sdk-ecs</artifactId>
                <version>2.0.0-rc2</version>
            </dependency>
            <dependency>
                <groupId>com.aliyun</groupId>
                <artifactId>aliyun-java-sdk-cms</artifactId>
                <version>2.0.0</version>
            </dependency>

二 创建aliyunoss.properties
文件内容:需要根据自己申请的账号进行配置,这里我用xxx代替
ACCESS_ID=xxx
ACCESS_KEY=xxx
OSS_ENDPOINT=xxx
bucketName=xxx

三.创建AliyunOssConfig.java 读取配置文件信息:

package com.zxm.cmds.aliyun;

import java.util.Properties;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

/**
 * 加载oss配置
 * 
 * @author Administrator
 *
 */
public class AliyunOssConfig {
    public static String ACCESS_ID = "";
    public static String ACCESS_KEY = "";
    public static String OSS_ENDPOINT = "";
    public static String bucketName = "";
    static Log log = LogFactory.getLog(AliyunOssConfig.class);

    public static void load() {
        log.info("oss配置加载开始  ....");
        Properties prop = new Properties();
        try {
            prop.load(AliyunOssConfig.class
    .getResourceAsStream("/config/aliyunoss.properties"));
            ACCESS_ID = prop.getProperty("ACCESS_ID");
            ACCESS_KEY = prop.getProperty("ACCESS_KEY");
            OSS_ENDPOINT = prop.getProperty(OSS_ENDPOINT);
            bucketName = prop.getProperty("bucketName");
        } catch (Exception e) {
            log.error("oss配置加载失败");
        }
    }

    /**
     * @return the aCCESS_ID
     */
    public static String getACCESS_ID() {
        return ACCESS_ID;
    }

    /**
     * @param aCCESS_ID
     *            the aCCESS_ID to set
     */
    public static void setACCESS_ID(String aCCESS_ID) {
        ACCESS_ID = aCCESS_ID;
    }

    /**
     * @return the aCCESS_KEY
     */
    public static String getACCESS_KEY() {
        return ACCESS_KEY;
    }

    /**
     * @param aCCESS_KEY
     *            the aCCESS_KEY to set
     */
    public static void setACCESS_KEY(String aCCESS_KEY) {
        ACCESS_KEY = aCCESS_KEY;
    }

    /**
     * @return the oSS_ENDPOINT
     */
    public static String getOSS_ENDPOINT() {
        return OSS_ENDPOINT;
    }

    /**
     * @param oSS_ENDPOINT
     *            the oSS_ENDPOINT to set
     */
    public static void setOSS_ENDPOINT(String oSS_ENDPOINT) {
        OSS_ENDPOINT = oSS_ENDPOINT;
    }

    /**
     * @return the bucketName
     */
    public static String getBucketName() {
        return bucketName;
    }

    /**
     * @param bucketName
     *            the bucketName to set
     */
    public static void setBucketName(String bucketName) {
        AliyunOssConfig.bucketName = bucketName;
    }

}

四.创建AliyunOssUtil.java 接口实现

package com.zxm.cmds.aliyun;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.InputStream;
import java.util.List;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import com.aliyun.oss.ClientException;
import com.aliyun.oss.OSSClient;
import com.aliyun.oss.OSSException;
import com.aliyun.oss.model.CannedAccessControlList;
import com.aliyun.oss.model.GetObjectRequest;
import com.aliyun.oss.model.OSSObjectSummary;
import com.aliyun.oss.model.ObjectListing;
import com.aliyun.oss.model.ObjectMetadata;



public class AliyunOssUtil {

    static Log log = LogFactory.getLog(AliyunOssUtil.class);

    public static void save(String key,String filePath){
        try{
        // 使用默认的OSS服务器地址创建OSSClient对象
        OSSClient client = new OSSClient(AliyunOssConfig.OSS_ENDPOINT,AliyunOssConfig.ACCESS_ID,AliyunOssConfig.ACCESS_KEY);
        ensureBucket(client, AliyunOssConfig.bucketName);
        setBucketPublicReadable(client, AliyunOssConfig.bucketName);
        System.out.println("正在上传...");
//      fileName = System.currentTimeMillis() + "." +getExtensionName(fileName);
       uploadFile(client, AliyunOssConfig.bucketName, key, filePath);
        }catch(Exception e){
            log.error("上传失败");
        }
    }

     // 如果Bucket不存在,则创建它。
    private static void ensureBucket(OSSClient client, String bucketName)
            throws OSSException, ClientException{

        if (client.isBucketExist(bucketName)){
            log.error("isBucketExist true");
            return;
        }

        //创建bucket
        client.createBucket(bucketName);
    }

    // 删除一个Bucket和其中的Objects 
    private static void deleteBucket(OSSClient client, String bucketName)
            throws OSSException, ClientException {

        ObjectListing ObjectListing = client.listObjects(bucketName);
        List<OSSObjectSummary> listDeletes = ObjectListing
                .getObjectSummaries();
        for (int i = 0; i < listDeletes.size(); i++) {
            String objectName = listDeletes.get(i).getKey();
            // 如果不为空,先删除bucket下的文件
            client.deleteObject(bucketName, objectName);
        }
        client.deleteBucket(bucketName);
    }

    // 把Bucket设置为所有人可读
    private static void setBucketPublicReadable(OSSClient client, String bucketName)
            throws OSSException, ClientException {
        //创建bucket
        client.createBucket(bucketName);

        //设置bucket的访问权限,public-read-write权限
        client.setBucketAcl(bucketName, CannedAccessControlList.PublicRead);
    }

    // 上传文件
    private static void  uploadFile(OSSClient client, String bucketName, String Objectkey, String filePath)
            throws OSSException, ClientException, FileNotFoundException {
        File file = new File(filePath);
        ObjectMetadata objectMeta = new ObjectMetadata();
        objectMeta.setContentLength(file.length());
        // 可以在metadata中标记文件类型
        if (filePath.endsWith("xml")) {
            objectMeta.setContentType("text/xml");
            }
            else if (filePath.endsWith("jpg")) {
            objectMeta.setContentType("image/jpeg");
            }
            else if (filePath.endsWith("png")) {
            objectMeta.setContentType("image/png");
            }
        InputStream input = new FileInputStream(file);
        client.putObject(bucketName, Objectkey, input, objectMeta);

    }

    // 下载文件
    private static void downloadFile(OSSClient client, String bucketName, String key, String filename)
            throws OSSException, ClientException {
        client.getObject(new GetObjectRequest(bucketName, key),
                new File(filename));
    }


    public static void main(String args[]){
        String key= "test.png";
        String filePath="F:\\test.png";
        save(key,filePath);
    }
}

调用save方法即可实现文件上传功能,注释很详细,应该大家都能看明白。

Logo

华为开发者空间,是为全球开发者打造的专属开发空间,汇聚了华为优质开发资源及工具,致力于让每一位开发者拥有一台云主机,基于华为根生态开发、创新。

更多推荐