java操作阿里云的对象存储OSS-阿里云开发者社区

开发者社区> 开发与运维> 正文
登录阅读全文

java操作阿里云的对象存储OSS

简介: 官网:: 对象存储(Object Storage Service,简称OSS) 以下博客简单介绍连接阿里云的OSS,新建Bucket,删除Bucket,向阿里云的OSS存储中存储单个文件,获取单个文件,删除单个文件等功能。 Api:: 开放式存储(OSS)Java API手册 1.0 documentation 以下为pom依赖: <!-- aliyun oss --

官网:: 对象存储(Object Storage Service,简称OSS)

以下博客简单介绍连接阿里云的OSS,新建Bucket,删除Bucket,向阿里云的OSS存储中存储单个文件,获取单个文件,删除单个文件等功能。

Api:: 开放式存储(OSS)Java API手册 1.0 documentation

以下为pom依赖:

		<!-- aliyun oss -->
		<dependency>
			<groupId>com.aliyun.oss</groupId>
			<artifactId>aliyun-sdk-oss</artifactId>
			<version>2.2.1</version>
		</dependency>

下载地址:Aliyun OSS SDK For Java » 2.2.1

下边为oss的配置文件oss.properties,也可以直接写入代码:

endpoint=oss-cn-beijing.aliyuncs.com
accessKeyId=您的key
accessKeySecret=您的secret

注endpoint为:OSS外网域名或OSS内网域名去掉您的Bucket.后

OSS的操作代码:

package my.demo.java.z.aliyun.oss;

import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.util.PropertyResourceBundle;
import java.util.ResourceBundle;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.aliyun.oss.OSSClient;
import com.aliyun.oss.model.Bucket;
import com.aliyun.oss.model.OSSObject;
import com.aliyun.oss.model.ObjectMetadata;
import com.aliyun.oss.model.PutObjectResult;

public class OSSUnit {
	
	//log
	private static final Logger LOG = LoggerFactory.getLogger(OSSUnit.class);
	
	//阿里云API的内或外网域名
	private static String ENDPOINT;
	//阿里云API的密钥Access Key ID
	private static String ACCESS_KEY_ID;
	//阿里云API的密钥Access Key Secret
	private static String ACCESS_KEY_SECRET;
	
	//init static datas
	static{
		ResourceBundle bundle = PropertyResourceBundle.getBundle("properties.oss");
		ENDPOINT = bundle.containsKey("endpoint") == false ? "" : bundle.getString("endpoint");
		ACCESS_KEY_ID = bundle.containsKey("accessKeyId") == false? "" : bundle.getString("accessKeyId");
		ACCESS_KEY_SECRET = bundle.containsKey("accessKeySecret") == false ? "" : bundle.getString("accessKeySecret");
	}
	
	/**
	 * 获取阿里云OSS客户端对象
	 * */
	public static final OSSClient getOSSClient(){
		return new OSSClient(ENDPOINT,ACCESS_KEY_ID, ACCESS_KEY_SECRET);
	}
	
	/**
	 * 新建Bucket  --Bucket权限:私有
	 * @param bucketName bucket名称
	 * @return true 新建Bucket成功
	 * */
	public static final boolean createBucket(OSSClient client, String bucketName){
		Bucket bucket = client.createBucket(bucketName); 
		return bucketName.equals(bucket.getName());
	}
	
	/**
	 * 删除Bucket 
	 * @param bucketName bucket名称
	 * */
	public static final void deleteBucket(OSSClient client, String bucketName){
		client.deleteBucket(bucketName); 
		LOG.info("删除" + bucketName + "Bucket成功");
	}
	
	/**
	 * 向阿里云的OSS存储中存储文件  --file也可以用InputStream替代
	 * @param client OSS客户端
	 * @param file 上传文件
	 * @param bucketName bucket名称
	 * @param diskName 上传文件的目录  --bucket下文件的路径
	 * @return String 唯一MD5数字签名
	 * */
	public static final String uploadObject2OSS(OSSClient client, File file, String bucketName, String diskName) {
		String resultStr = null;
		try {
			InputStream is = new FileInputStream(file);
			String fileName = file.getName();
			Long fileSize = file.length();
			//创建上传Object的Metadata
			ObjectMetadata metadata = new ObjectMetadata();
			metadata.setContentLength(is.available());
			metadata.setCacheControl("no-cache");
			metadata.setHeader("Pragma", "no-cache");
			metadata.setContentEncoding("utf-8");
			metadata.setContentType(getContentType(fileName));
			metadata.setContentDisposition("filename/filesize=" + fileName + "/" + fileSize + "Byte.");
			//上传文件 
			PutObjectResult putResult = client.putObject(bucketName, diskName + fileName, is, metadata);
			//解析结果
			resultStr = putResult.getETag();
		} catch (Exception e) {
			LOG.error("上传阿里云OSS服务器异常." + e.getMessage(), e);
		}
		return resultStr;
	}
	
    /** 
     * 根据key获取OSS服务器上的文件输入流
 	 * @param client OSS客户端
 	 * @param bucketName bucket名称
 	 * @param diskName 文件路径
 	 * @param key Bucket下的文件的路径名+文件名
     */  
     public static final InputStream getOSS2InputStream(OSSClient client, String bucketName, String diskName, String key){ 
		OSSObject ossObj = client.getObject(bucketName, diskName + key);
		return ossObj.getObjectContent();	
     }  
	
   /** 
    * 根据key删除OSS服务器上的文件 
  	* @param client OSS客户端
  	* @param bucketName bucket名称
  	* @param diskName 文件路径
  	* @param key Bucket下的文件的路径名+文件名
    */  
	  public static void deleteFile(OSSClient client, String bucketName, String diskName, String key){  
	  	client.deleteObject(bucketName, diskName + key); 
	  	LOG.info("删除" + bucketName + "下的文件" + diskName + key + "成功");
	  }  
     
    /** 
     * 通过文件名判断并获取OSS服务文件上传时文件的contentType 
     * @param fileName 文件名
     * @return 文件的contentType   
     */  
     public static final String getContentType(String fileName){  
    	String fileExtension = fileName.substring(fileName.lastIndexOf("."));
    	if("bmp".equalsIgnoreCase(fileExtension)) return "image/bmp";
    	if("gif".equalsIgnoreCase(fileExtension)) return "image/gif";
    	if("jpeg".equalsIgnoreCase(fileExtension) || "jpg".equalsIgnoreCase(fileExtension)  || "png".equalsIgnoreCase(fileExtension) ) return "image/jpeg";
    	if("html".equalsIgnoreCase(fileExtension)) return "text/html";
    	if("txt".equalsIgnoreCase(fileExtension)) return "text/plain";
    	if("vsd".equalsIgnoreCase(fileExtension)) return "application/vnd.visio";
    	if("ppt".equalsIgnoreCase(fileExtension) || "pptx".equalsIgnoreCase(fileExtension)) return "application/vnd.ms-powerpoint";
    	if("doc".equalsIgnoreCase(fileExtension) || "docx".equalsIgnoreCase(fileExtension)) return "application/msword";
    	if("xml".equalsIgnoreCase(fileExtension)) return "text/xml";
        return "text/html";  
     }  

}

代码对应测试代码junit如下:

package my.demo.java.z.aliyun.oss;

import static org.junit.Assert.assertEquals;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;

import org.junit.Before;
import org.junit.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.aliyun.oss.OSSClient;

public class OSSUnitTest {
	
	//log
	private static final Logger LOG = LoggerFactory.getLogger(OSSUnitTest.class);
	
	private OSSUnit ossunit = null;
	private OSSClient client = null;
	private String bucketName = "oss-test-my";
	@Before
	public void initUnit(){
		ossunit = new OSSUnit();
		client = OSSUnit.getOSSClient();
	}

	@Test
	public void testCreateBucket() {
		String bucketName = "oss-test-my";
		//创建bucket
		assertEquals(true, OSSUnit.createBucket(client, bucketName));
	}
	
	@Test
	public void testDeleteBucket(){
		String bucketName = "oss-test-my";
		//删除bucket
		OSSUnit.deleteBucket(client, bucketName);
		//console log :删除oss-test-myBucket成功
	}
	
	@Test
	public void testUploadObject2OSS(){
		//上传文件
		String flilePathName = "C:/Users/Tony_tian/Desktop/csdnimg/preossimg.jpg";
		File file = new File(flilePathName);
		String diskName = "datas/image/";
		String md5key = OSSUnit.uploadObject2OSS(client, file, bucketName, diskName);
		LOG.info("上传后的文件MD5数字唯一签名:" + md5key);  //上传后的文件MD5数字唯一签名:A30B046A34EB326C4A3BBD784333B017
	}
	
	@Test
	public void testGetOSS2InputStream(){
		//获取文件
		try {
			BufferedInputStream bis = new BufferedInputStream(OSSUnit.getOSS2InputStream(client, bucketName, "datas/image/", "preossimg.jpg"));
			String resfile = "C:/Users/Tony_tian/Desktop/csdnimg/preossimg_res.jpg";
			BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(new File(resfile)));
			int itemp = 0;
			while((itemp = bis.read()) != -1){
				bos.write(itemp);
			}
			LOG.info("文件获取成功"); //console log :文件获取成功
			bis.close();
			bos.close();
		} catch (Exception e) {
			LOG.error("从OSS获取文件失败:" + e.getMessage(), e);
		}
	}
	
	@Test
	public void testDeleteFile(){
		//注:文件夹下只有一个文件,则文件夹也会一起删除;如果多个文件,只会删除指定文件名的文件
		//删除文件
		OSSUnit.deleteFile(client, bucketName, "datas/image/", "preossimg.jpg");
		//console log : 删除oss-test-my下的文件datas/image/preossimg.jpg成功
	}

}
部分效果图:

新建Bucket(Bucket权限:私有,公开需手动设置)前后和删除Bucket:




上传文件前后即删除文件:

注:文件夹下只有一个文件,则文件夹也会一起删除;如果多个文件,只会删除指定文件名的文件




上边记录为私有文件的获取,如果要获取“Bucket权限:公共读”的就很简单了:

<!DOCTYPE html>
<html>
	<head>
		<meta charset="utf-8" />
		<title>Aliyun-OSS</title>
		<meta name="keywords" content="Aliyun-OSS"/>
		<meta name="description" content="Aliyun-OSS" />
	<!--	<link rel="stylesheet" href="${serverprc }/static/css/common.css" />
		<script type="text/javascript" src="${serverprc }/static/js/common.js" charset="utf-8"></script> -->
	</head>
	<body>
		<div>
			Bucket权限:公共读的图片:<img src="http://tsxs-datas.oss-cn-beijing.aliyuncs.com/image/public/tsxs_title_logo.ico"/>
		</div>
	</body>
</html>
打开效果:


版权声明:本文内容由阿里云实名注册用户自发贡献,版权归原作者所有,阿里云开发者社区不拥有其著作权,亦不承担相应法律责任。具体规则请查看《阿里云开发者社区用户服务协议》和《阿里云开发者社区知识产权保护指引》。如果您发现本社区中有涉嫌抄袭的内容,填写侵权投诉表单进行举报,一经查实,本社区将立刻删除涉嫌侵权内容。

分享:
开发与运维
使用钉钉扫一扫加入圈子
+ 订阅

集结各类场景实战经验,助你开发运维畅行无忧

其他文章