关注分享主机优惠活动
国内外VPS云服务器

阿里oss工具类(阿里OSS桶)

参考博客阿里门户配置信息配置文件工具类上传文件到阿里本地文件。保存在Ali中的文件名可以包含路径,并返回上传文件的访问路径。如果上传时需要设置存储类型和访问权限,请参考下面的示例代码。遍历所有要关闭的文件。

参考博客:阿里OSS简介

存储桶配置信息:alios.properties

OSS配置文件:AliOSSConfig.java @数据公共类aliossconfig {私有字符串端点;私有字符串accessKeyId私有字符串accessKeySecret私有字符串bucketNameprivate AliOSSConfig(){ Properties Properties = new Properties();try { properties . load(a lioss config . class . getresourceasstream("/OSS/a lioss . properties "));} catch(io exception e){ e . printstacktrace();} endpoint = properties . getproperty(" endpoint ");access keyid = properties . getproperty(" access keyid ");accesskey secret = properties . getproperty(" accesskey secret ");bucket name = properties . getproperty(" bucket name ");}私有静态AliOSSConfig实例= new AliOSSConfig();公共静态AliOSSConfig getInstance(){ return instance;}}工具类:AliOSSUtil.java公共类aliossutil { private static final string endpoint = aliossconfig . getinstance()。get endpoint();私有静态最终字符串access keyid = aliossconfig . getinstance()。getAccessKeyId();私有静态最终字符串accessKeySecret = aliossconfig . getinstance()。getAccessKeySecret();私有静态最终字符串bucket name = aliossconfig . getinstance()。getbucket name();/* * *上传文件到Ali OSS * * @ param source file pathname本地文件* @param aimFilePathName保存在Ali OSS中可以包含路径的文件名* @return返回上传文件的访问路径* @ throwsfilenotfoundexception */public static String uploading(String source file pathname,String aimFilePathName)抛出file not found exception { file inputstream is = new file inputstream(source file pathname);if(aim file pathname . starts with("/)){ aim file pathname = aim file pathname . substring(1);}//如果上传时需要设置存储类型和访问权限,请参考下面的示例代码。ObjectMetadata元数据= new object metadata();int indexOfLastDot = aim file pathname . lastindexof(" . ");String后缀= aimfilepathname . substring(indexOfLastDot);metadata . set content type(get content type(后缀));//避免文件覆盖目标文件路径名=目标文件路径名。Substring (0,lastdot的索引)+system。current time millis()+后缀;PutObjectRequest PutObjectRequest = new PutObjectRequest(bucket name,aimFilePathName,is);//访问PutObjectRequest时避免下载图片。设置元数据(metadata);OSS OSS client = new OSS client builder()。build(endpoint,accessKeyId,accesskey secret);OSS client . putobject(putObjectRequest);日期到期=新日期(system . current time millis()+3600 l * 1000 * 24 * 365 * 100);URL URL = OSS client . generatepresignedurl(bucket name,aimFilePathName,expiration);//关闭OSS client . shut down();返回URL . tostring();}/* *网络实现上传头像到OSS * * @ param multipart file * @ return */public static string upload(multipart file multipart file)。抛出IOException {//获取上传文件的输入流file = multipartfile。getinputstream();//获取文件名string filename = multipart file . getoriginalfilename();//避免文件覆盖int i = fileName.lastIndexOf(" . ");字符串后缀= filename . substring(I);fileName = fileName.substring(0,I)+system . current time millis()+suffix;//按日期分类文件//获取当前日期字符串datepath = datetime formatter . iso _ date . format(local date . now());//拼接文件名filename = date path+"/"+filename;//如果需要上传,设置存储类型和访问权限。对象元数据metadata =新对象元数据();metadata . set content type(get content type(filename . substring(filename . lastindexof(" . "))));//上传文件到OSS时,需要指定包括文件后缀的完整路径,比如ABC/EFG/123.jpg..PutObjectRequest PutObjectRequest = new PutObjectRequest(bucket name,fileName,inputStream);putObjectRequest.setMetadata(元数据);OSS OSS client = new OSS client builder()。build(endpoint,accessKeyId,accesskey secret);OSS client . putobject(putObjectRequest);//文件访问路径dateexpiration = newdate (system。currenttimemillis()+3600 l * 1000 * 24 * 365 * 100);URL URL = OSS client . generatepresignedurl(bucket name,fileName,expiration);//关闭OSS client . shut down();//返回上传到oss的路径,返回URL . tostring();}/* * * returns content type * * @ param文件扩展名* @ return */private static String get content type(String filename extension){ if(filename extension . equalsignorecase("。BMP ")){ return " image/BMP ";} if(filename extension . equalsignorecase("。gif ")){ return " image/gif ";} if(filename extension . equalsignorecase("。JPEG ")| | filename extension . equalsignorecase("。jpg ")| | filename extension . equalsignorecase("。png ")){ return " image/jpg ";}返回“image/jpg”;}/* * *列出指定路径下所有文件的文件名*如果要列出根路径下的所有文件,path = " * * @ param path * @ return */public static list filename(string path){ list RES = new ArrayList();//构造ListObjectsRequest请求。ListObjectsRequest ListObjectsRequest = new ListObjectsRequest(bucket name);//设置prefix参数获取fun目录下的所有文件。listObjectsRequest.setPrefix(路径);OSS OSS client = new OSS client builder()。build(endpoint,accessKeyId,accesskey secret);//列出文件。object listing listing = OSS client . listobjects(listobjects request);//遍历(ossiobjectsummary object summary:listing . getobjectsummarys()){ system . out . println(object summary . getkey())的所有文件;}//关闭OSS客户端。OSS client . shut down();返回res}/* * *列出file */public static listlistfile url(string path){ listres = new ArrayList()下的所有文件URL信息;//构造ListObjectsRequest请求ListObjectsRequest ListObjectsRequest = new ListObjectsRequest(bucket name);//设置prefix参数获取fun目录下的所有文件。listObjectsRequest.setPrefix(路径);OSS OSS client = new OSS client builder()。build(endpoint,accessKeyId,accesskey secret);//列出文件。object listing listing = OSS client . listobjects(listobjects request);//遍历所有文件。For (ossiobjectsummary对象摘要:列表。getobject summaries()){//文件访问路径dateexpiration = newdate (system。currenttimemillis()+3600 l * 1000 * 24 * 365 * 100);URL URL = OSS client . generatepresignedurl(bucket name,objectSummary.getKey(),expiration);RES . add(URL . tostring());}//关闭OSS客户端。OSS client . shut down();返回res}/* * *判断文件是否存在* * @ param object name * @ return */public static boolean is file exist(string object name)。{ OSS OSS client = new OSS client builder()。build(endpoint,accessKeyId,accesskey secret);boolean RES = OSS client . doesobjectexist(bucket name,object name);返回res}/* * *按文件名下载文件* * @param objectName文件名下载* @param localFileName文件名本地创建*/public static void Download File(String object name,String local filename){ OSS OSS client = new OSS client builder()。build(endpoint,accessKeyId,accesskey secret);//将OSS文件下载到本地文件。如果指定的本地文件存在,它将被覆盖;如果不存在,将会创建它。OSS client . getobject(new getobject request(bucket name,objectName),new File(local filename));//关闭OSSClient。OSS client . shut down();}/* * *删除文件或目录* * @ param object name */public static void Delete file(String object name)。{ OSS OSS client = new OSS client builder()。build(endpoint,accessKeyId,accesskey secret);OSS client . delete object(bucket name,object name);OSS client . shut down();}/* * *批量删除文件或目录* * @ param keys */public static void Delete files(list keys){ OSS client = new OSS lient builder()。build (endpoint,accesskeyid,access keys ecret);//删除文件。DeleteObjectsResult DeleteObjectsResult = OSS client . delete objects(new DeleteObjectsRequest(bucket name))。with keys(keys));Java . util . list deleted objects = deleteobjectsresult . getdeletedobjects();OSS client . shut down();}/* * * Create folder * * @ param folder * @ return */public static string Create folder(string folder){//folder name final string keysuffixwithslash = folder;OSS OSS client = new OSS client builder()。build(endpoint,accessKeyId,accesskey secret);//判断文件夹是否存在,如果不存在,创建一个if(!OSS client . doesobjectexist(bucket name,keysuffixwitlash)){//创建文件夹ossclient.putobject (bucket name,keysuffixwitlash,new byte数组输入流(new byte[0]);//获取文件夹名ossobjectobject = OSS client . getobject(桶名,keysuffixwithslash);string fileDir = object . getkey();OSS client . shut down();返回fileDir} return keySuffixWithSlash}}注意:为了避免OSS link中的连接池关闭错误,不要在类中创建OSSClient对象,因为如果这样做,所有的方法都会共享这个实例对象,并在短时间内在前端连续提交,从而导致异常。OSSClient对象应该在方法中创建。

测试代码classaliossutitest { @ test void upload()抛出文件not found exception {//上传文件stringurl = aliossutil . upload(" e://picture//510 . jpg ","/aa/bb/ba . jpg ");system . out . println(URL);} @ Test void List filename(){ List RES = aliossutil . List filename(" aa/");RES . foreach(system . out::println);} @ Test void listFileUrl(){ List RES = aliossutil . listFileUrl(" aa/");RES . foreach(system . out::println);} @ Test void isfile exist(){ boolean RES = aliossutil . isfile exist(" aa/bb/ab 1637160001528 . jpg ");system . out . println(RES);} @ Test void download file(){ aliossutil . download file(" aa/bb/ab 1637160001528 . jpg "," d:/aawer . jpg ");} @ Test void delete file(){ aliossutil . delete file(" aa/bb/ab 1637160001528 . jpg ");} @ Test void delete files(){ List keys = List . of(" aa/bb/ab 1637160001528 . jpg "," aa/bb/ba1637160268079.jpg "," aa/bb/cc ");AliOSSUtil.deleteFiles(密钥);} @ Test void create folder(){ String folder = aliossutil . create folder(" aa/bb/cc ");System.out.println(文件夹);}}

未经允许不得转载:主机频道 » 阿里oss工具类(阿里OSS桶)

评论 抢沙发

评论前必须登录!