阿里云OSS对象存储的使用

news/2024/11/23 5:09:36/

所需jar包

                <!-- oss文件服务器--><dependency><groupId>com.aliyun.oss</groupId><artifactId>aliyun-sdk-oss</artifactId><version>2.8.3</version></dependency>

工具类:

OSSUploadUtil

package com.hxf.application.util.ossfileutil;import com.aliyun.oss.ClientException;
import com.aliyun.oss.OSSClient;
import com.aliyun.oss.OSSException;
import com.aliyun.oss.model.*;
import org.springframework.stereotype.Component;import java.io.*;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.UUID;/*** @program: demo* @description: oss* @create: 2018-12-18 17:08**/
@Component
public class OSSUploadUtil {private static OSSConfig config = null;private static final SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");/*** @param file* @param fileType 文件后缀* @oaram business 业务目录* @return String 文件地址* @MethodName: uploadFile* @Description: OSS单文件上传*/public static String uploadFile(File file, String fileType,String business) {config = config == null ? new OSSConfig() : config;String fileName =   business +"/"+sdf.format(new Date()) +"/"+ UUID.randomUUID().toString().toUpperCase().replace("-", "") + "." + fileType; //文件名,根据UUID来return putObject(file, fileType, fileName);}/*** @param file* @param fileType 文件后缀* @return String 文件地址* @MethodName: uploadFile* @Description: OSS单文件上传*/public static String uploadFile(File file, String fileType) {config = config == null ? new OSSConfig() : config;String fileName =  sdf.format(new Date()) +"/"+ UUID.randomUUID().toString().toUpperCase().replace("-", "") + "." + fileType; //文件名,根据UUID来return putObject(file, fileType, fileName);}/*** @param file* @param fileType* @param oldUrl* @return String* @MethodName: updateFile* @Description: 更新文件:只更新内容,不更新文件名和文件地址。* (因为地址没变,可能存在浏览器原数据缓存,不能及时加载新数据,例如图片更新,请注意)*/public static String updateFile(File file, String fileType, String oldUrl) {if (oldUrl == null) return null;return putObject(file, fileType, oldUrl);}/*** @param file* @param fileType 文件后缀* @param oldUrl   需要删除的文件地址* @return String 文件地址* @MethodName: replaceFile* @Description: 替换文件:删除原文件并上传新文件,文件名和地址同时替换* 解决原数据缓存问题,只要更新了地址,就能重新加载数据)*/public static String replaceFile(File file, String fileType, String oldUrl) {boolean flag = deleteFile(oldUrl);      //先删除原文件if (!flag) {//更改文件的过期时间,让他到期自动删除。}return uploadFile(file, fileType);}/*** @param fileUrl 需要删除的文件url* @return boolean 是否删除成功* @MethodName: deleteFile* @Description: 单文件删除*/public static boolean deleteFile(String fileUrl) {config = config == null ? new OSSConfig() : config;String url = "http://" +config.getBucketName() + "." + config.getEndpoint() + fileUrl;String bucketName = OSSUploadUtil.getBucketName(url);       //根据url获取bucketNameString fileName = OSSUploadUtil.getFileName(url);           //根据url获取fileNameif (bucketName == null || fileName == null) return false;OSSClient ossClient = null;try {ossClient = new OSSClient(config.getEndpoint(), config.getAccessKeyId(), config.getAccessKeySecret());GenericRequest request = new DeleteObjectsRequest(bucketName).withKey(fileName);ossClient.deleteObject(request);} catch (Exception oe) {oe.printStackTrace();return false;} finally {ossClient.shutdown();}return true;}/*** @param fileUrls 需要删除的文件url集合* @return int 成功删除的个数* @MethodName: batchDeleteFiles* @Description: 批量文件删除(较快):适用于相同endPoint和BucketName*/public static int deleteFile(List<String> fileUrls) {int deleteCount = 0;    //成功删除的个数String bucketName = OSSUploadUtil.getBucketName(fileUrls.get(0));       //根据url获取bucketNameList<String> fileNames = OSSUploadUtil.getFileName(fileUrls);         //根据url获取fileNameif (bucketName == null || fileNames.size() <= 0) return 0;OSSClient ossClient = null;try {ossClient = new OSSClient(config.getEndpoint(), config.getAccessKeyId(), config.getAccessKeySecret());DeleteObjectsRequest request = new DeleteObjectsRequest(bucketName).withKeys(fileNames);DeleteObjectsResult result = ossClient.deleteObjects(request);deleteCount = result.getDeletedObjects().size();} catch (OSSException oe) {oe.printStackTrace();throw new RuntimeException("OSS服务异常:", oe);} catch (ClientException ce) {ce.printStackTrace();throw new RuntimeException("OSS客户端异常:", ce);} finally {ossClient.shutdown();}return deleteCount;}/*** @param fileUrls 需要删除的文件url集合* @return int 成功删除的个数* @MethodName: batchDeleteFiles* @Description: 批量文件删除(较慢):适用于不同endPoint和BucketName*/public static int deleteFiles(List<String> fileUrls) {int count = 0;for (String url : fileUrls) {if (deleteFile(url)) {count++;}}return count;}/*** @param file* @param fileType* @param fileName* @return String* @MethodName: putObject* @Description: 上传文件*/private static String putObject(File file, String fileType, String fileName) {config = config == null ? new OSSConfig() : config;String url = null;      //默认nullOSSClient ossClient = null;try {ossClient = new OSSClient(config.getEndpoint(), config.getAccessKeyId(), config.getAccessKeySecret());InputStream input = new FileInputStream(file);ObjectMetadata meta = new ObjectMetadata();             // 创建上传Object的Metadatameta.setContentType(OSSUploadUtil.contentType(fileType));       // 设置上传内容类型meta.setCacheControl("no-cache");                   // 被下载时网页的缓存行为PutObjectRequest request = new PutObjectRequest(config.getBucketName(), fileName, input, meta);           //创建上传请求ossClient.putObject(request);//url = "http://" +config.getBucketName() + "." + config.getEndpoint() + "/" + fileName;       //上传成功再返回的文件路径url = fileName;       //上传成功再返回域名后文件路径} catch (OSSException oe) {oe.printStackTrace();return null;} catch (ClientException ce) {ce.printStackTrace();return null;} catch (FileNotFoundException e) {e.printStackTrace();return null;} finally {ossClient.shutdown();}return url;}/*** @param fileType* @return String* @MethodName: contentType* @Description: 获取文件类型*/private static String contentType(String fileType) {fileType = fileType.toLowerCase();String contentType = "";switch (fileType) {case "bmp":contentType = "image/bmp";break;case "gif":contentType = "image/gif";break;case "png":case "jpeg":case "jpg":contentType = "image/jpeg";break;case "html":contentType = "text/html";break;case "txt":contentType = "text/plain";break;case "vsd":contentType = "application/vnd.visio";break;case "ppt":case "pptx":contentType = "application/vnd.ms-powerpoint";break;case "doc":case "docx":contentType = "application/msword";break;case "xml":contentType = "text/xml";break;case "mp4":contentType = "video/mp4";break;default:contentType = "application/octet-stream";break;}return contentType;}/*** @param fileUrl 文件url* @return String bucketName* @MethodName: getBucketName* @Description: 根据url获取bucketName*/private static String getBucketName(String fileUrl) {String http = "http://";String https = "https://";int httpIndex = fileUrl.indexOf(http);int httpsIndex = fileUrl.indexOf(https);int startIndex = 0;if (httpIndex == -1) {if (httpsIndex == -1) {return null;} else {startIndex = httpsIndex + https.length();}} else {startIndex = httpIndex + http.length();}int endIndex = fileUrl.indexOf(".oss-");return fileUrl.substring(startIndex, endIndex);}/*** @param fileUrl 文件url* @return String fileName* @MethodName: getFileName* @Description: 根据url获取fileName*/public static String getFileName(String fileUrl) {String str = config.getBucketName()+"."+config.getEndpoint();int beginIndex = fileUrl.indexOf(str);if (beginIndex == -1) return null;return fileUrl.substring(beginIndex + str.length());}/*** @param fileUrls 文件url* @return List<String>  fileName集合* @MethodName: getFileName* @Description: 根据url获取fileNames集合*/private static List<String> getFileName(List<String> fileUrls) {List<String> names = new ArrayList<>();for (String url : fileUrls) {names.add(getFileName(url));}return names;}/****  文件下载* @param name* @return* @throws IOException*/public  static InputStream download (String name) throws IOException {config = config == null ? new OSSConfig() : config;// 创建OSSClient实例。OSSClient ossClient = new OSSClient(config.getEndpoint(), config.getAccessKeyId(), config.getAccessKeySecret());// ossObject包含文件所在的存储空间名称、文件名称、文件元信息以及一个输入流。OSSObject ossObject = ossClient.getObject(config.getBucketName(), name);// 读取文件内容。InputStream is = ossObject.getObjectContent();// 关闭OSSClient。ossClient.shutdown();return is;}}
OSSFileUtil
package com.hxf.application.util.ossfileutil;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.util.List;/*** @program: * @description: OSS服务器操作工具类* @create: 2018-12-19 01:45**/
@Component
public class OSSFileUtil {/**** 单个上传* @param is* @param business 业务分区* @return 返回域名后路径* @throws IOException*/public static String  UploadFile(MultipartFile is , String business) throws IOException {String fileSuffixName = is.getOriginalFilename().substring(is.getOriginalFilename().lastIndexOf(".")+1);File f = null;if(is.equals("")||is.getSize()<=0){is = null;}else{InputStream ins = is.getInputStream();f=new File(is.getOriginalFilename());OSSUtil.inputStreamToFile(ins, f);}String s=   OSSUploadUtil.uploadFile(f,fileSuffixName,business);File del = new File(f.toURI());del.delete();return s;}/**** 多个上传* @param list* @param business 业务分区* @return  返回域名后路径* @throws IOException*/public static String  UploadFileList(List<MultipartFile> list , String business) throws IOException {String s="";for (MultipartFile is: list) {String fileSuffixName = is.getOriginalFilename().substring(is.getOriginalFilename().lastIndexOf(".")+1);File f = null;if(is.equals("")||is.getSize()<=0){is = null;}else{InputStream ins = is.getInputStream();f=new File(is.getOriginalFilename());OSSUtil.inputStreamToFile(ins, f);}OSSUploadUtil.uploadFile(f,fileSuffixName,business);File del = new File(f.toURI());del.delete();}return s;}/**** 文件更新* @param is* @param oldurl 需要更新的url* @return 返回更新后域名后路径* @throws IOException*/public static String  UpdateFile (MultipartFile is,String oldurl) throws IOException {String fileSuffixName = is.getOriginalFilename().substring(is.getOriginalFilename().lastIndexOf(".")+1);File f = null;if(is.equals("")||is.getSize()<=0){is = null;}else{InputStream ins = is.getInputStream();f=new File(is.getOriginalFilename());OSSUtil.inputStreamToFile(ins, f);}String s=   OSSUploadUtil.updateFile(f,fileSuffixName,oldurl);File del = new File(f.toURI());del.delete();return s;}/**** 文件删除* @param url* @throws IOException*/public static boolean DeleteFile(String url) {boolean s=   OSSUploadUtil.deleteFile(url);return s ;}}
OSSConfig
package com.hxf.application.util.ossfileutil;import java.io.IOException;/*** @program: demo* @description: oss配置类* @create: 2018-12-18 17:03**/
public class OSSConfig {private  String endpoint;       //连接区域地址private  String accessKeyId;    //连接keyIdprivate  String accessKeySecret;//连接秘钥private  String bucketName;     //需要存储的bucketNameprivate  String picLocation;    //图片保存路径public OSSConfig() {try {this.endpoint = SystemConfig.getConfigResource("endpoint");this.bucketName = SystemConfig.getConfigResource("bucketName");this.picLocation = SystemConfig.getConfigResource("picLocation");this.accessKeyId = SystemConfig.getConfigResource("accessKeyId");this.accessKeySecret = SystemConfig.getConfigResource("accessKeySecret");} catch (IOException e) {e.printStackTrace();}}public String getEndpoint() {return endpoint;}public void setEndpoint(String endpoint) {this.endpoint = endpoint;}public String getAccessKeyId() {return accessKeyId;}public void setAccessKeyId(String accessKeyId) {this.accessKeyId = accessKeyId;}public String getAccessKeySecret() {return accessKeySecret;}public void setAccessKeySecret(String accessKeySecret) {this.accessKeySecret = accessKeySecret;}public String getBucketName() {return bucketName;}public void setBucketName(String bucketName) {this.bucketName = bucketName;}public String getPicLocation() {return picLocation;}public void setPicLocation(String picLocation) {this.picLocation = picLocation;}
}
加载配置文件类SystemConfig
package com.hxf.application.util.ossfileutil;import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;/*** @program: demo* @description:* @create: 2018-12-18 17:04**/
public class SystemConfig {private static final String CONFIG_PROPERTIES="config.properties";public static String getConfigResource(String key) throws IOException {ClassLoader loader = Thread.currentThread().getContextClassLoader();Properties properties = new Properties();InputStream in = loader.getResourceAsStream(CONFIG_PROPERTIES);properties.load(in);String value = properties.getProperty(key);// 编码转换,从ISO-8859-1转向指定编码value = new String(value.getBytes("ISO-8859-1"), "UTF-8");in.close();return value;}
}

配置文件config.properties

#阿里云OSS
endpoint = *********
bucketName = ***-***-***
picLocation =
accessKeyId = L*********8
accessKeySecret = c************************p

记录OSS对象存储,有问题麻烦帮忙指出来,我方便及时修正


http://www.ppmy.cn/news/883788.html

相关文章

集成推送后,阿里云旺初始化失败的解决办法

app需要同时集成聊天和推送功能&#xff0c;经过调研&#xff0c;聊天决定选用阿里的sdk&#xff08;百川云旺&#xff09;。 经过一个星期的努力&#xff0c;聊天的功能开发完成&#xff0c;推送顺便用了之前用过的百度推送。在模拟器上运行挺正常的&#xff0c;接收推送&…

阿里旺旺(不是掏宝旺旺)

<a href" http://amos.im.alisoft.com/msg.aw?v2&amp;uidsongshicong&amp;sitecnalichn&amp;s1&amp;charsetutf-8" target"_blank"><font color"#666666"><img alt"点击这里给我发消息" border"…

无线端自定义模块html编辑,关于阿里巴巴无线端旺铺自定义模块如何设置图片全屏自动适应的问题...

无线端旺铺最近已经是被阿里放到了非常重要的一个层次&#xff0c;各种数据(%&#xffe5;…………&&此处省略一万字)总之&#xff0c;就是很牛逼啦&#xff01; 然后呢~最近很多朋友通过微信、旺旺群问我&#xff0c;无线端里面的自定义页面&#xff0c;图片需要做多大…

Android集成阿里云旺即时通讯踩坑历程

下载云旺的demo&#xff0c;将demo中的OneSDK直接拷贝&#xff0c;作为Moudle进行依赖&#xff0c;具体操作就不说了&#xff0c;OneSDK是最新的&#xff0c;一定不要进行修改&#xff0c; 进行依赖后&#xff0c;可能会遇到buildToolsVersion 版本不一致&#xff0c;换过来就…

阿里云ARMS渲染速度指标

前言 大家都知道&#xff0c;首屏性能对点击率、转换率等有很大影响&#xff0c;以下是我们统计的淘宝旺铺点击率和首屏时间的关系&#xff0c;随着首屏时间从1秒增大到8秒&#xff0c;点击率逐步从 85%降低到了82%【来自阿里云ARMS前端监控团队】 指标和标准 指标说明 ARM…

java实现阿里云短信服务发送验证码

在写注册接口时&#xff0c;需引入短信第三方接口&#xff0c;故使用了阿里云短信服务&#xff0c;在这里简单描述一下 1.引入依赖 <!--手机发送短信验证码--><dependency><groupId>com.aliyun</groupId><artifactId>aliyun-java-sdk-core</…

阿里云旺(客服)使用指南

1.在libs 添加 两个包 IMCore-2.0.1 IMKit-2.0.1 直接加在libs 的下面 不用加任何文件夹 2.代码块 在 application 的文件进行初始化 具体代码如下 初始化 入口 public void initImKitData() { //必须首先执行这部分代码, 如果在":TCMSSevice&q…

阿里云-网站备案基本流程(2019.7)

一、什么是备案 根据 《互联网信息服务管理办法》 以及 《非经营性互联网信息服务备案管理办法》 &#xff0c;国家对非经营性互联网信息服务实行备案制度&#xff0c;对经营性互联网信息服务实行许可制度。未取得许可或者未履行备案手续的&#xff0c;不得从事互联网信息服务…