package com.tlzn.tkwl.oss;
import com.aliyun.oss.ClientException;
import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.OSSException;
import com.aliyun.oss.model.*;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.util.List;
/**
- 创建存储空间
*/
@RestController
@RequestMapping(“/bucket/ibucket”)
public class BucketSpace {
// 设置外网访问域名
private static String endpoint = "a";
private static String accessKeyId = "b";
private static String accessKeySecret = "c";
static OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);
/* // 创建OSSClient实例。
@RequestMapping(value = “/createBucket”)
public static String createBucket(String bucketName){
try {
if (ossClient.doesBucketExist(bucketName)) {
return "您已经创建Bucket:" + bucketName + "。";
} else {
System.out.println("您的Bucket不存在,创建Bucket:" + bucketName + "。");
return ossClient.createBucket(bucketName).getName();
}
} catch (OSSException oe) {
return "Error Message:" + oe.getErrorMessage();
} catch (ClientException ce) {
return "Error Message:" + ce.getMessage();
} finally {
if (ossClient != null) {
ossClient.shutdown();
}
}
}
*//**
* 列举存储空间
*//*
@RequestMapping(value = "/getBucketList")
public static String getBucketList( ){
try {
// 列举当前账号下的所有存储空间。
List<Bucket> buckets = ossClient.listBuckets();
for (Bucket bucket : buckets) {
System.out.println(" - " + bucket.getName());
}
} catch (OSSException oe) {
return "Error Message:" + oe.getErrorMessage();
} catch (ClientException ce) {
System.out.println("Caught an ClientException, which means the client encountered "
+ "a serious internal problem while trying to communicate with OSS, "
+ "such as not being able to access the network.");
return("Error Message:" + ce.getMessage());
} finally {
if (ossClient != null) {
ossClient.shutdown();
}
}
return null;
}
//删除空间
@RequestMapping(value = "/delBucketList")
public static String delBucketList(String bucketName){
try {
// 删除存储空间。
ossClient.deleteBucket(bucketName);
} catch (OSSException oe) {
return("Host ID:" + oe.getHostId());
} catch (ClientException ce) {
return("Error Message:" + ce.getMessage());
} finally {
if (ossClient != null) {
ossClient.shutdown();
}
}
return null;
}
*/
/**
* 文件流上传文件
* @param bucketName 空间名称
* @param objectName 上传的地址
* @param filePath 本地的文件地址
* @return
* @throws FileNotFoundException
*/
@RequestMapping(value = "/uploadIOFile")
public static String uploadIOFile(String bucketName,String objectName,String filePath) throws FileNotFoundException {
bucketName = "空间名";
objectName = "测试1/测试1/测试1/测试图片.jpg";
// 填写本地文件的完整路径,例如D:\\localpath\\examplefile.txt。
// 如果未指定本地路径,则默认从示例程序所属项目对应本地路径中上传文件流。
filePath= "D:\\目录啊\\测试图片.jpg";
// 创建OSSClient实例。
OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);
try {
InputStream inputStream = new FileInputStream(filePath);
// 创建PutObject请求。
ossClient.putObject(bucketName, objectName, inputStream);
} catch (OSSException oe) {
return "Error Message:" + oe.getMessage();
} catch (ClientException ce) {
return "Error Message:" + ce.getMessage();
} finally {
if (ossClient != null) {
ossClient.shutdown();
}
}
return null;
}
/**
* 文件流上传文件
* @param bucketName 空间名称
* @param objectName 上传的地址
* @param filePath 本地的文件地址
* @return
* @throws FileNotFoundException
*/
@RequestMapping(value = "/uploadFile")
public static String uploadFile(String bucketName,String objectName,String filePath) throws FileNotFoundException {
// 填写Object完整路径,完整路径中不能包含Bucket名称,例如exampledir/exampleobject.txt。
objectName = "测试1/测试文件2.docx";
// 填写本地文件的完整路径,例如D:\\localpath\\examplefile.txt。
// 如果未指定本地路径,则默认从示例程序所属项目对应本地路径中上传文件。
filePath= "D:\\目录啊\\测试文件1.docx";
// 创建OSSClient实例。
OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);
try {
// 创建PutObjectRequest对象。
PutObjectRequest putObjectRequest = new PutObjectRequest(bucketName, objectName, new File(filePath));
// 如果需要上传时设置存储类型和访问权限,请参考以下示例代码。
// ObjectMetadata metadata = new ObjectMetadata();
// metadata.setHeader(OSSHeaders.OSS_STORAGE_CLASS, StorageClass.Standard.toString());
// metadata.setObjectAcl(CannedAccessControlList.Private);
// putObjectRequest.setMetadata(metadata);
// 上传文件。
ossClient.putObject(putObjectRequest);
// ossClient.getObject(new GetObjectRequest(bucketName, objectName), new File(“D:\目录啊\测试文件13.docx”));
} catch (OSSException oe) {
return “Error Message:” + oe.getMessage();
} catch (ClientException ce) {
return “Error Message:” + ce.getMessage();
} finally {
if (ossClient != null) {
ossClient.shutdown();
}
}
return null;
}
/**
* 下载io文件
* @param bucketName 空间名称
* @param objectName 文件所在的路径
* @throws FileNotFoundException
*/
@RequestMapping(value = "/downloadIOFile")
public static void downloadIOFile( String bucketName,String objectName ) throws FileNotFoundException {
// 填写Object完整路径,完整路径中不能包含Bucket名称,例如exampledir/exampleobject.txt。
objectName = "测试1/测试文件2.docx";
// 创建OSSClient实例。
OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);
try {
// ossObject包含文件所在的存储空间名称、文件名称、文件元信息以及一个输入流。
OSSObject ossObject = ossClient.getObject("空间名", objectName);
// 读取文件内容。
BufferedReader reader = new BufferedReader(new InputStreamReader(ossObject.getObjectContent()));
while (true) {
String line = reader.readLine();
if (line == null) break;
}
// 数据读取完成后,获取的流必须关闭,否则会造成连接泄漏,导致请求无连接可用,程序无法正常工作。
reader.close();
// ossObject对象使用完毕后必须关闭,否则会造成连接泄漏,导致请求无连接可用,程序无法正常工作。
ossObject.close();
} catch (OSSException oe) {
System.out.println("Caught an OSSException, which means your request made it to OSS, "
+ "but was rejected with an error response for some reason.");
} catch (Throwable ce) {
System.out.println("Caught an ClientException, which means the client encountered "
+ "a serious internal problem while trying to communicate with OSS, "
+ "such as not being able to access the network.");
} finally {
if (ossClient != null) {
ossClient.shutdown();
}
}
}
/**
* 下载到本地
* @param bucketName 空间名称
* @param objectName 文件所在的路径
* @param pathName 下载本地路径
* @return
* @throws FileNotFoundException
*/
@RequestMapping(value = "/downloadFile")
public static String downloadFile(String bucketName, String objectName,String pathName) throws FileNotFoundException {
// 填写Bucket名称,例如examplebucket。
bucketName ="空间名";
// 填写不包含Bucket名称在内的Object完整路径,例如testfolder/exampleobject.txt。
// String objectName = “测试1/测试文件2.docx”;
objectName = “测试1/测试图片.jpg”;
pathName = “D:\目录啊\测试图片sss.jpg”;
// 创建OSSClient实例。
OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);
try {
// 下载Object到本地文件,并保存到指定的本地路径中。如果指定的本地文件存在会覆盖,不存在则新建。
// 如果未指定本地路径,则下载后的文件默认保存到示例程序所属项目对应本地路径中。
ossClient.getObject(new GetObjectRequest(bucketName, objectName), new File(pathName));
} catch (OSSException oe) {
return oe.getMessage();
} catch (ClientException ce) {
return ce.getMessage();
} finally {
if (ossClient != null) {
ossClient.shutdown();
}
}
return null;
}
/**
* 下载OSS服务器的文件
*
* @param objectName
* @param response
*/
@RequestMapping(value = "/downOSSFile")
@ResponseBody
public void downOSSFile(String objectName, HttpServletResponse response) {
BufferedInputStream input = null;
OutputStream outputStream = null;
OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);
objectName = "测试1/测试图片.jpg";
OSSObject ossObject = ossClient.getObject("空间名", objectName);
String fileName = ossObject.getKey().substring(ossObject.getKey().lastIndexOf("/")+1);
try {
response.reset();
response.setCharacterEncoding("utf-8");
response.setContentType("application/x-msdownload");
response.addHeader("Content-Disposition",
"attachment;filename=" + new String(fileName.getBytes("gb2312"), "ISO8859-1"));
input = new BufferedInputStream(ossObject.getObjectContent());
byte[] buffBytes = new byte[1024];
outputStream = response.getOutputStream();
int read = 0;
while ((read = input.read(buffBytes)) != -1) {
outputStream.write(buffBytes, 0, read);
}
outputStream.flush();
// 数据读取完成后,获取的流必须关闭,否则会造成连接泄漏,导致请求无连接可用,程序无法正常工作。
ossObject.close();
} catch (IOException ex) {
ex.printStackTrace();
} finally {
try {
if (outputStream != null) {
outputStream.close();
}
if (input != null) {
input.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
ossClient.shutdown();
}
/**
* 删除文件
* @param bucketName
* @param objectName
* @param pathName
* @return
* @throws FileNotFoundException
*/
@RequestMapping(value = "/deleteObject")
public static String deleteObject(String bucketName, String objectName,String pathName) throws FileNotFoundException {
// 填写Bucket名称,例如examplebucket。
bucketName ="空间名";
// 填写不包含Bucket名称在内的Object完整路径,例如testfolder/exampleobject.txt。
// String objectName = “测试1/测试文件2.docx”;
objectName = “测试1/测试图片.jpg”;
// 创建OSSClient实例。
OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);
try {
// 下载Object到本地文件,并保存到指定的本地路径中。如果指定的本地文件存在会覆盖,不存在则新建。
// 如果未指定本地路径,则下载后的文件默认保存到示例程序所属项目对应本地路径中。
ossClient.deleteObject(bucketName, objectName);
} catch (OSSException oe) {
return oe.getMessage();
} catch (ClientException ce) {
return ce.getMessage();
} finally {
if (ossClient != null) {
ossClient.shutdown();
}
}
return null;
}
}