记录代码,如有错误,希望大家能够指出问题。
官网地址:
对象存储 OSS - 帮助中心 - 阿里云https://help.aliyun.com/product/31815.html
阿里云对象存储OSS(Object Storage Service)是一款海量、安全、低成本、高可靠的云存储服务,可提供99.9999999999%(12个9)的数据持久性,99.995%的数据可用性。多种存储类型供选择,全面优化存储成本。
OSS具有与平台无关的RESTful API接口,您可以在任何应用、任何时间、任何地点存储和访问任意类型的数据。
您可以使用阿里云提供的API、SDK接口或者OSS迁移工具轻松地将海量数据移入或移出阿里云OSS。数据存储到阿里云OSS以后,您可以选择标准存储(Standard)作为移动应用、大型网站、图片分享或热点音视频的主要存储方式,也可以选择成本更低、存储期限更长的低频访问存储(Infrequent Access)、归档存储(Archive)、冷归档存储(Cold Archive)作为不经常访问数据的存储方式。
以上摘录官网。
1.maven 依赖
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.4.1</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<groupId>com.example</groupId>
<artifactId>demo</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>demo</name>
<description>Demo project for Spring Boot</description>
<properties>
<java.version>1.8</java.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter</artifactId>
</dependency>
<dependency>
<groupId>com.aliyun.oss</groupId>
<artifactId>aliyun-sdk-oss</artifactId>
<version>3.10.2</version>
</dependency>
<dependency>
<groupId>com.aliyun</groupId>
<artifactId>aliyun-java-sdk-core</artifactId>
<version>[4.4.9,5.0.0)</version>
</dependency>
<dependency>
<groupId>com.aliyun</groupId>
<artifactId>aliyun-java-sdk-imm</artifactId>
<optional>true</optional>
<version>1.22.0</version>
</dependency>
<dependency>
<groupId>com.google.code.gson</groupId>
<artifactId>gson</artifactId>
<version>2.8.5</version>
</dependency>
<dependency>
<groupId>commons-fileupload</groupId>
<artifactId>commons-fileupload</artifactId>
<version>1.3.3</version>
</dependency>
<dependency>
<groupId>commons-io</groupId>
<artifactId>commons-io</artifactId>
<version>2.5</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-jdbc</artifactId>
</dependency>
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>1.3.2</version>
</dependency>
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid-spring-boot-starter</artifactId>
<version>1.1.10</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.28</version>
<scope>runtime</scope>
</dependency>
</dependencies>
</project>
2、controller
package com.example.demo.controller;
import com.aliyun.oss.model.ObjectListing;
import com.example.demo.config.OSSProperties;
import com.example.demo.utils.OSSUtil;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
@RestController
public class uploadPhoto {
@RequestMapping("/hello")
public String helloWorld() {
return "nihao";
}
/**
* 多图片上传
*
* @param fileList
* @return
*/
@RequestMapping("/uploads")
public String checkList(List<MultipartFile> fileList) {
String photoUrl = "";
OSSUtil ossClient = new OSSUtil();
try {
for (int i = 0; i < fileList.size(); i++) {
//将文件上传
String name = ossClient.uploadImg2Oss(fileList.get(i));
//获取文件的URl地址 以便前台 显示
String imgUrl = ossClient.getImgUrl(name);
if (i == 0) {
photoUrl = imgUrl;
} else {
photoUrl += "," + imgUrl;
}
}
} catch (Exception e) {
e.printStackTrace();
}
return photoUrl.trim();
}
/**
* 单文件上传
*
* @param imgFile
* @param req
* @return
* @throws Exception
*/
@RequestMapping("/upload")
public Map<String, Object> uploadPhoto(@RequestParam("imgFile") MultipartFile imgFile, HttpServletRequest req) {
OSSUtil ossClient = new OSSUtil();
Map<String, Object> m = new HashMap<>();
if (imgFile.isEmpty()) {
m.put("error", "上传文件不能为空");
}
String newsUrl = "";
if (!(imgFile).isEmpty()) {
try {
//将文件上传
String name = ossClient.uploadImg2Oss(imgFile);
//获取文件的URl地址 以便前台 显示
String imgUrl = ossClient.getImgUrl(name);
m.put("url", imgUrl);
} catch (IOException e) {
e.printStackTrace();
}
} else {
m.put("error", "上传图片不可为空");
}
return m;
}
/**
* 获取oss文件
*
* @param key
* @return
*/
@RequestMapping("/onlineSee")
public Map<String, Object> onlineSee(String key) {
OSSUtil ossClient = new OSSUtil();
Map<String, Object> m = new HashMap<>();
String strings = ossClient.onlineSee(key);
m.put("url", strings);
return m;
}
/**
* 文档预览
*
* @param key
* @return
*/
@RequestMapping("/onlinePreview")
public Map<String, Object> onlinePreview(String key) {
OSSUtil ossClient = new OSSUtil();
Map<String, Object> m = new HashMap<>();
Object strings = ossClient.onlinePreview(key);
m.put("url", strings);
return m;
}
/**
* 获取文件
*
* @param key
* @return
*/
@RequestMapping("/getUrl")
public Map<String, Object> getUrl(String key) {
OSSUtil ossClient = new OSSUtil();
Map<String, Object> m = new HashMap<>();
String strings = ossClient.getUrl(key);
m.put("url", strings);
return m;
}
/**
* 获取文件夹
*
* @param fileName
* @return
*/
@RequestMapping("/fileFolder")
public Map<String, Object> fileFolder(String fileName) {
Map<String, Object> m = new HashMap<>();
OSSUtil ossClient = new OSSUtil();
List<String> strings = ossClient.fileFolder(fileName);
m.put("fileFolder", strings);
return m;
}
/**
* 通过文件名下载文件
*
* @param objectName
* @param localFileName
* @return
*/
@RequestMapping(value = "/downloadFile", method = RequestMethod.GET)
public void downloadFile( HttpServletResponse response, String objectName, String localFileName) {
try {
OSSUtil ossClient = new OSSUtil();
ossClient.downloadFile(response, objectName, localFileName);
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* 删除文件
*
* @param key
* @return
*/
@RequestMapping(value = "/deleteObject", method = RequestMethod.POST)
public void deleteObject(String key) {
try {
OSSUtil ossClient = new OSSUtil();
ossClient.delFile(key);
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* 获取文件夹下文件列表
*
* @param fileHost
* @return
*/
@RequestMapping("/listFile")
public Map<String, Object> listFile(String fileHost, String nextMarker) {
OSSUtil ossClient = new OSSUtil();
Map<String, Object> m = new HashMap<>();
List<String> strings = ossClient.listFile(fileHost, nextMarker);
m.put("listFile", strings);
return m;
}
/**
* 获取文件夹下文件列表和文件夹
*
* @param fileHost
* @return
*/
@RequestMapping("/listFile2")
public Map<String, Object> listFile2(String fileHost, String nextMarker) {
OSSUtil ossClient = new OSSUtil();
Map<String, Object> m = new HashMap<>();
ObjectListing strings = ossClient.listFile2(fileHost, nextMarker);
m.put("listFile", strings);
return m;
}
/**
* 创建文件夹
*
* @param folder
* @return
*/
@RequestMapping("/createFolder")
public Map<String, Object> createFolder(String folder) {
Map<String, Object> m = new HashMap<>();
try {
OSSUtil ossClient = new OSSUtil();
String reFolder = ossClient.createFolder(folder);
m.put("reFolder", reFolder);
} catch (Exception e) {
e.printStackTrace();
m.put("error", "请输入文件名");
}
return m;
}
/**
* 后台提供获取secretAccessKey,accessKeyId接口
*
* @param
* @return
*/
@RequestMapping("/ossConfig")
public Map<String, Object> ossConfig() {
Map<String, Object> m = new HashMap<>();
try {
String aliyunAccessKey = OSSProperties.ALIYUN_ACCESS_KEY;
String aliyunAccessId = OSSProperties.ALIYUN_ACCESS_ID;
m.put("aliyunAccessKey", aliyunAccessKey);
m.put("aliyunAccessId", aliyunAccessId);
} catch (Exception e) {
e.printStackTrace();
}
return m;
}
}
3、工具类
package com.example.demo.utils;
import com.alibaba.druid.util.StringUtils;
import com.aliyun.oss.HttpMethod;
import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.model.*;
import com.example.demo.config.OSSProperties;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.multipart.MultipartFile;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URL;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Random;
public class OSSUtil {
/**
* log日志
*/
public static final Logger logger = LoggerFactory.getLogger(OSSUtil.class);
private static final String endpoint = OSSProperties.ALIYUN_ENDPOINT;
private static final String accessKeyId = OSSProperties.ALIYUN_ACCESS_ID;
private static final String accessKeySecret = OSSProperties.ALIYUN_ACCESS_KEY;
private static final String bucketName = OSSProperties.ALIYUN_BUCKET;
private static final String FOLDER = OSSProperties.ALIYUN_DIR;
/**
* 获取oss
*
* @return
*/
public static OSS getOSSClient() {
return new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);
}
/**
* 上传图片
*
* @param url
* @throws
*/
public void uploadImg2Oss(String url) throws IOException {
File fileOnServer = new File(url);
FileInputStream fin;
try {
fin = new FileInputStream(fileOnServer);
String[] split = url.split("/");
this.uploadFile2OSS(fin, split[split.length - 1]);
} catch (FileNotFoundException e) {
throw new IOException("图片上传失败");
}
}
public String uploadImg2Oss(MultipartFile file) throws IOException {
/* if (file.getSize() > 10 * 1024 * 1024) {
throw new IOException("上传图片大小不能超过10M!");
}*/
String originalFilename = file.getOriginalFilename();
String substring = originalFilename.substring(originalFilename.lastIndexOf(".")).toLowerCase();
Random random = new Random();
String name = random.nextInt(10000) + System.currentTimeMillis() + substring;
System.out.println(System.currentTimeMillis());
System.out.println(name);
System.out.println(random.nextInt(10000));
// name = DateUtils.dateStr(new Date(), "yyyy/MM/dd") + "/" + System.currentTimeMillis() + substring;
try {
InputStream inputStream = file.getInputStream();
this.uploadFile2OSS(inputStream, name);
return name;
} catch (Exception e) {
e.printStackTrace();
throw new IOException("图片上传失败");
}
}
/**
* 获得图片路径
*
* @param fileUrl
* @return
*/
public String getImgUrl(String fileUrl) {
System.out.println(fileUrl);
if (!StringUtils.isEmpty(fileUrl)) {
String[] split = fileUrl.split("/");
return this.getUrl(this.FOLDER + split[split.length - 1]);
}
return "";
}
/**
* 上传到OSS服务器 如果同名文件会覆盖服务器上的
*
* @param instream 文件流
* @param fileName 文件名称 包括后缀名
* @return 出错返回"" ,唯一MD5数字签名
*/
public String uploadFile2OSS(InputStream instream, String fileName) {
String ret = "";
try {
OSS ossClient = getOSSClient();
// 创建上传Object的Metadata
ObjectMetadata objectMetadata = new ObjectMetadata();
objectMetadata.setContentLength(instream.available());
objectMetadata.setCacheControl("no-cache");
objectMetadata.setContentType(getContentType(fileName.substring(fileName.lastIndexOf("."))));
objectMetadata.setHeader("Pragma", "no-cache");
// objectMetadata.setContentDisposition("inline;filename=" + fileName);
// 上传文件
PutObjectResult putResult = ossClient.putObject(bucketName, FOLDER + fileName, instream, objectMetadata);
ret = putResult.getETag();
} catch (IOException e) {
logger.error(e.getMessage(), e);
} finally {
try {
if (instream != null) {
instream.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
return ret;
}
/**
* 通过文件名判断并获取OSS服务文件上传时文件的contentType
*
* @param filenameExtension 文件名
* @return 文件的contentType
*/
public static final String getContentType(String filenameExtension) {
if (filenameExtension.equalsIgnoreCase(".bmp")) {
return "application/x-bmp";
}
if (filenameExtension.equalsIgnoreCase(".gif")) {
return "image/gif";
}
if (filenameExtension.equalsIgnoreCase(".jpeg") ||
filenameExtension.equalsIgnoreCase(".jpg") ||
filenameExtension.equalsIgnoreCase(".png")) {
return "image/jpg";
}
if (filenameExtension.equalsIgnoreCase(".html")) {
return "text/html";
}
if (filenameExtension.equalsIgnoreCase(".txt")) {
return "text/plain";
}
if (filenameExtension.equalsIgnoreCase(".vsd")) {
return "application/vnd.visio";
}
if (filenameExtension.equalsIgnoreCase(".pptx") ||
filenameExtension.equalsIgnoreCase(".ppt")) {
return "application/vnd.ms-powerpoint";
}
if (filenameExtension.equalsIgnoreCase(".docx") ||
filenameExtension.equalsIgnoreCase(".doc")) {
return "application/msword";
}
if (filenameExtension.equalsIgnoreCase(".xla") ||
filenameExtension.equalsIgnoreCase(".xlc") ||
filenameExtension.equalsIgnoreCase(".xlm") ||
filenameExtension.equalsIgnoreCase(".xls") ||
filenameExtension.equalsIgnoreCase(".xlt") ||
filenameExtension.equalsIgnoreCase(".xlw")) {
return "application/vnd.ms-excel";
}
if (filenameExtension.equalsIgnoreCase(".xlsx")) {
return "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
}
if (filenameExtension.equalsIgnoreCase(".xml")) {
return "text/xml";
}
if (filenameExtension.equalsIgnoreCase(".pdf")) {
return "application/pdf";
}
if (filenameExtension.equalsIgnoreCase(".zip")) {
return "application/zip";
}
if (filenameExtension.equalsIgnoreCase(".tar")) {
return "application/x-tar";
}
if (filenameExtension.equalsIgnoreCase(".avi")) {
return "video/avi";
}
if (filenameExtension.equalsIgnoreCase(".mp4")) {
return "video/mpeg4";
}
if (filenameExtension.equalsIgnoreCase(".mp3")) {
return "audio/mp3";
}
if (filenameExtension.equalsIgnoreCase(".mp2")) {
return "audio/mp2";
}
// 默认下载
// return "application/octet-stream";
return "image/jpg";
}
/**
* 获得url链接
*
* @param key
* @return
*/
public String getUrl(String key) {
// 设置URL过期时间为10年 3600l* 1000*24*365*10
OSS ossClient = getOSSClient();
Date expiration = new Date(System.currentTimeMillis() + 3600L * 1000 * 24 * 365 * 10);
// 生成URL
URL url = ossClient.generatePresignedUrl(bucketName, key, expiration);
if (url != null) {
String host = "https://" + url.getHost() + url.getPath();
return host;
}
return "";
}
/**
* 获取文件夹
*
* @param fileName
* @return
*/
public List<String> fileFolder(String fileName) {
// 创建OSSClient实例。
OSS ossClient = getOSSClient();
// 构造ListObjectsRequest请求。
ListObjectsRequest listObjectsRequest = new ListObjectsRequest(bucketName);
// 设置正斜线(/)为文件夹的分隔符。
listObjectsRequest.setDelimiter("/");
// 设置prefix参数来获取fun目录下的所有文件。
if (!StringUtils.isEmpty(fileName)) {
listObjectsRequest.setPrefix(fileName + "/");
}
// 列出文件
ObjectListing listing = ossClient.listObjects(listObjectsRequest);
// 遍历所有commonPrefix
List<String> list = new ArrayList<>();
for (String commonPrefix : listing.getCommonPrefixes()) {
String newCommonPrefix = commonPrefix.substring(0, commonPrefix.length() - 1);
String[] s = newCommonPrefix.split("/");
if (!StringUtils.isEmpty(fileName)) {
list.add(s[s.length - 1]);
} else {
list.add(s[0]);
}
}
// 关闭OSSClient
ossClient.shutdown();
return list;
}
/**
* 列举文件下所有的文件url信息
*/
public ObjectListing listFile2(String fileHost, String nextMarker) {
// 创建OSSClient实例。
OSS ossClient = getOSSClient();
// 构造ListObjectsRequest请求。
ListObjectsRequest listObjectsRequest = new ListObjectsRequest(bucketName);
// 设置正斜线(/)为文件夹的分隔符。
listObjectsRequest.setDelimiter("/");
// 列出fun目录下的所有文件和文件夹。
listObjectsRequest.setPrefix(fileHost + "/");
ObjectListing listing = ossClient.listObjects(listObjectsRequest);
// 遍历所有文件。
System.out.println("Objects:");
// objectSummaries的列表中给出的是fun目录下的文件。
for (OSSObjectSummary objectSummary : listing.getObjectSummaries()) {
System.out.println(objectSummary.getKey());
}
// 遍历所有commonPrefix。
System.out.println("\nCommonPrefixes:");
// commonPrefixs列表中显示的是fun目录下的所有子文件夹。由于fun/movie/001.avi和fun/movie/007.avi属于fun文件夹下的movie目录,因此这两个文件未在列表中。
for (String commonPrefix : listing.getCommonPrefixes()) {
System.out.println(commonPrefix);
}
// 关闭OSSClient。
ossClient.shutdown();
return listing;
}
/**
* 列举文件下所有的文件url信息
*/
public List<String> listFile(String fileHost, String nextMarker) {
// 创建OSSClient实例。
OSS ossClient = getOSSClient();
// 构造ListObjectsRequest请求
ListObjectsRequest listObjectsRequest = new ListObjectsRequest(bucketName);
// 设置prefix参数来获取fun目录下的所有文件。
listObjectsRequest.setPrefix(fileHost + "/");
listObjectsRequest.setMarker(nextMarker);
// 列出文件。
ObjectListing listing = ossClient.listObjects(listObjectsRequest);
// 遍历所有文件。
List<String> list = new ArrayList<>();
for (int i = 0; i < listing.getObjectSummaries().size(); i++) {
String FILE_URL = "https://" + bucketName + "." + endpoint + "/" + listing.getObjectSummaries().get(i).getKey();
list.add(FILE_URL);
}
// 关闭OSSClient。
ossClient.shutdown();
// ObjectListing objectListing = null;
// int total = 0;
// HashMap<Integer, String> markerMap = new HashMap<>();
// try {
// ObjectListing objectListing2 = null;
// do {
// String nextMarker2 = objectListing2 != null ? objectListing2.getNextMarker() : null;
// ListObjectsRequest listObjectsRequest2 = new ListObjectsRequest(bucketName).withMarker(nextMarker2).withMaxKeys(100);
// listObjectsRequest2.setPrefix(fileHost + "/");
// objectListing2 = ossClient.listObjects(listObjectsRequest2);
// total += (objectListing2 != null && objectListing2.getObjectSummaries() != null ? objectListing2.getObjectSummaries().size() : 0);
// markerMap.put(markerMap.size() + 1, nextMarker2);
// } while (objectListing2 != null && !StringUtils.isEmpty(objectListing2.getNextMarker()));
//
// ListObjectsRequest listObjectsRequest = new ListObjectsRequest(bucketName).withMarker(nextMarker).withMaxKeys(100);
//
// listObjectsRequest.setPrefix(fileHost + "/");
//
// objectListing = ossClient.listObjects(listObjectsRequest);
// for (int i = 0; i < objectListing.getObjectSummaries().size(); i++) {
// String FILE_URL = "https://" + bucketName + "." + endpoint + "/" + objectListing.getObjectSummaries().get(i).getKey();
// list.add(FILE_URL);
// }
//
// } catch (Exception e) {
//
// } finally {
// // 关闭client
// ossClient.shutdown();
// }
return list;
}
/**
* 删除文件
* objectName key 地址
*
* @param filePath
*/
public Boolean delFile(String filePath) {
// 创建OSSClient实例。
OSS ossClient = getOSSClient();
// 删除Object.
boolean exist = ossClient.doesObjectExist(bucketName, filePath);
if (!exist) {
return false;
}
ossClient.deleteObject(bucketName, filePath);
ossClient.shutdown();
return true;
}
/**
* 批量删除
*
* @param keys
*/
public Boolean delFileList(List<String> keys) {
// 创建OSSClient实例。
OSS ossClient = getOSSClient();
try {
// 删除文件。
DeleteObjectsResult deleteObjectsResult = ossClient.deleteObjects(new DeleteObjectsRequest(bucketName).withKeys(keys));
List<String> deletedObjects = deleteObjectsResult.getDeletedObjects();
} catch (Exception e) {
e.printStackTrace();
return false;
} finally {
ossClient.shutdown();
}
return true;
}
/**
* 创建文件夹
*
* @param folder
* @return
*/
public String createFolder(String folder) {
// 创建OSSClient实例。
OSS ossClient = getOSSClient();
// 文件夹名
final String keySuffixWithSlash = folder;
// 判断文件夹是否存在,不存在则创建
if (!ossClient.doesObjectExist(bucketName, keySuffixWithSlash)) {
// 创建文件夹
ossClient.putObject(bucketName, keySuffixWithSlash, new ByteArrayInputStream(new byte[0]));
// 得到文件夹名
OSSObject object = ossClient.getObject(bucketName, keySuffixWithSlash);
String fileDir = object.getKey();
ossClient.shutdown();
return fileDir;
}
return keySuffixWithSlash;
}
/**
* 通过文件名下载文件
*
* @param objectName 要下载的文件名
* @param localFileName 本地要创建的文件名
*/
public void downloadFile(HttpServletResponse response, String objectName, String localFileName) throws Exception {
// 创建OSSClient实例。
OSS ossClient = getOSSClient();
try {
// ossObject包含文件所在的存储空间名称、文件名称、文件元信息以及一个输入流。
OSSObject ossObject = ossClient.getObject(bucketName, objectName);
// 读去Object内容 返回
BufferedInputStream in = new BufferedInputStream(ossObject.getObjectContent());
BufferedOutputStream out = new BufferedOutputStream(response.getOutputStream());
//通知浏览器以附件形式下载
response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(objectName, "utf-8"));
//BufferedOutputStream out=new BufferedOutputStream(new FileOutputStream(new File("f:\\a.txt")));
byte[] car = new byte[1024];
int L = 0;
while ((L = in.read(car)) != -1) {
out.write(car, 0, L);
}
if (out != null) {
out.flush();
out.close();
}
if (in != null) {
in.close();
}
} catch (Exception e) {
e.printStackTrace();
} finally {
// 关闭OSSClient。
ossClient.shutdown();
}
}
public String onlineSee(String key) {
// 创建OSSClient实例。
OSS ossClient = getOSSClient();
// 设置URL过期时间为1小时
Date expiration = new Date(new Date().getTime() + 3600 * 1000);
// 临时地址
URL url = ossClient.generatePresignedUrl(bucketName, key, expiration);
// 关闭OSSClient。
ossClient.shutdown();
return url.toString();
}
public Object onlinePreview(String key) {
// 创建OSSClient实例。
OSS ossClient = getOSSClient();
// 设置视频截帧操作。文档页数默认是200,EndPage_-1任意
String style = "imm/previewdoc,EndPage_-1";
String filenameExtension = key.substring(key.lastIndexOf("."));
if (filenameExtension.equalsIgnoreCase(".pdf")) {
style = "imm/previewdoc,EndPage_-1,PdfVector_true";
}
// 指定过期时间为1小时。
Date expiration = new Date(new Date().getTime() + 1000 * 60 * 60);
GeneratePresignedUrlRequest req = new GeneratePresignedUrlRequest(bucketName, key, HttpMethod.GET);
req.setExpiration(expiration);
req.setProcess(style);
URL signedUrl = ossClient.generatePresignedUrl(req);
return signedUrl;
}
public static void main(String[] args) {
}
}
4、配置类
package com.example.demo.config;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.PropertySource;
import org.springframework.stereotype.Component;
@Component
@PropertySource("classpath:/aliyun.properties")
public class OSSProperties implements InitializingBean {
@Value("${aliyun.endpoint}")
private String aliyun_endpoint;
@Value("${aliyun.access-id}")
private String aliyun_access_id;
@Value("${aliyun.access-key}")
private String aliyun_access_key;
@Value("${aliyun.bucket}")
private String aliyun_bucket;
@Value("${aliyun.dir}")
private String aliyun_dir;
//声明静态变量,
public static String ALIYUN_ENDPOINT;
public static String ALIYUN_ACCESS_ID;
public static String ALIYUN_ACCESS_KEY;
public static String ALIYUN_BUCKET;
public static String ALIYUN_DIR;
@Override
public void afterPropertiesSet() throws Exception {
ALIYUN_ENDPOINT = aliyun_endpoint;
ALIYUN_ACCESS_ID = aliyun_access_id;
ALIYUN_ACCESS_KEY = aliyun_access_key;
ALIYUN_BUCKET = aliyun_bucket;
ALIYUN_DIR = aliyun_dir;
}
}
5、阿里云配置数据
aliyun.access-id=
aliyun.access-key=
aliyun.bucket=
aliyun.endpoint=
aliyun.dir=