比尔云BierYun--阿里云最新优惠活动
阿里云优惠码丨阿里云代金券

阿里云oss服务器文件上传java

阿里云oss服务器文件上传javahttp://www.bieryun.com/1251.html

前天做OSS服务器文件上传,之前没了解过,做的过程中遇到许多问题,最终通过查阅相关资料解决了,特分享一下。

首先准备工作必要的jar

这里注意版本一致,不然就会报很多坑爹的错误..

如果你断点调试在执行putObject方法时报错,99%的是罐子包有问题..

然后是配置文件

现在开通OSS,都是免费开通的,包年9块钱。

这是几个必要的参数,既然做这个肯定要知道的!这里就不多做解释了。

这里,首先需要我们创建一个OSS 信息实体类,OSSCon 图。Java,用来读取配置文件的信息,封装成实体。

[java] 查看纯文本

  1. import  java.io.IOException;
  2. import  java.io.InputStream;
  3. import  java.util.Properties;
  4.   / **
  5.    * oss相关参数实体
  6.    * @author liux
  7.    * 2017年/ 5/5
  8.    * /
  9. 公共 OSSConfigure {
  10.     私人 字符串端点;
  11.     私人 字符串accessKeyId;
  12.     私人 字符串accessKeySecret;
  13.     私人 字符串bucketName;
  14.     私人 字符串accessUrl;
  15.     public  OSSConfigure(){
  16.     }
  17.     / ** 
  18.      *通过配置文件.properties文件获取,这几项内容。 
  19.      *  
  20.      * @param storageConfName 
  21.      * @抛出IOException 
  22.      * /
  23.     公共 OSSConfigure(字符串storageConfName)  抛出 IOException {
  24.         属性prop =  new  Properties();
  25.         InputStream is =  super .getClass()。getClassLoader()。getResourceAsStream(storageConfName);
  26.         prop.load(是);
  27.         endpoint = prop.getProperty(“Endpoint” ).trim();
  28.         accessKeyId = prop.getProperty(“AccessKey” ).trim();
  29.         accessKeySecret = prop.getProperty(“AccessKeySecret” ).trim();
  30.         bucketName = prop.getProperty(“BucketName” ).trim();
  31.         accessUrl = prop.getProperty(“accessUrl” ).trim();
  32.     }
  33.     公共 OSSConfigure(字符串端点,字符串accessKeyId,
  34.             字符串accessKeySecret,字符串bucketName,字符串accessUrl){
  35.         这个.endpoint =端点;
  36.         这个.accessKeyId = accessKeyId;
  37.         这个.accessKeySecret = accessKeySecret;
  38.         这个.bucketName = bucketName;
  39.         这个.accessUrl = accessUrl;
  40.     }
  41.     public  String getEndpoint(){
  42.         返回 终点;
  43.     }
  44.     public void  setEndpoint(String endpoint){
  45.         这个.endpoint =端点;
  46.     }
  47.     public  String getAccessKeyId(){
  48.         返回 accessKeyId;
  49.     }
  50.     public void  setAccessKeyId(String accessKeyId){
  51.         这个.accessKeyId = accessKeyId;
  52.     }
  53.     public  String getAccessKeySecret(){
  54.         返回 accessKeySecret;
  55.     }
  56.     public void  setAccessKeySecret(String accessKeySecret){
  57.         这个.accessKeySecret = accessKeySecret;
  58.     }
  59.     public  String getBucketName(){
  60.         返回 bucketName;
  61.     }
  62.     public void  setBucketName(String bucketName){
  63.         这个.bucketName = bucketName;
  64.     }
  65.     public  String getAccessUrl(){
  66.         返回 accessUrl;
  67.     }
  68.     public void  setAccessUrl(String accessUrl){
  69.         这个.accessUrl = accessUrl;
  70.     }
  71. }

 

然后就是创建一个OSS文件管理的OSSManageUtil工具类的.oss文件存储实际上就是对对象的操作,只要写好路径,都会自动创建的,OSSClient是OSS的核心,有兴趣的可以多研究下。我做这个是要上传app,以及压缩图片后上传,contentType这个方法注意,我上传的是所以要用这个类型application / octet-stream,之前因为这个找了半天错。

[java] 查看纯文本

  1.  com.cdy.utils;
  2. import  java.io.File;
  3. import  java.io.IOException;
  4. import  java.io.InputStream;
  5. import  java.util.Date;
  6. import  com.aliyun.oss.ClientException;
  7. import  com.aliyun.oss.OSSClient;
  8. import  com.aliyun.oss.OSSException;
  9. import  com.aliyun.oss.model.GetObjectRequest;
  10. import  com.aliyun.oss.model.OSSObject;
  11. import  com.aliyun.oss.model.ObjectMetadata;
  12. / **
  13.  *对OSS服务器进行上传删除等的处理
  14.  * 
  15.  * @ClassName:OSSManageUtil
  16.  * @说明:
  17.  * @author liux
  18.  * @date 2017-5-3上午10:47:00
  19.  * 
  20.  * /
  21. 公共 OSSManageUtil {
  22.     / **
  23.      *上传OSS服务器文件@Title:uploadFile 
  24.      * @param multipartFile spring上传的文件
  25.      * remotePath @param oss服务器二级目录
  26.      * @throws Exception设定文件@return String
  27.      *返回类型@throws
  28.      * /
  29.     public static  String uploadFile(InputStream fileContent,String remotePath,String fileName)  throws  Exception {
  30.         //随机名处理
  31.         fileName =  “lxkc_”  +  new  Date()。getTime()+ fileName.substring(fileName.lastIndexOf(“。” ));
  32.         //加载配置文件,初始化OSSClient
  33.         OSSConfigure ossConfigure =  new  OSSConfigure(“/ system.properties );
  34.         OSSClient ossClient =  新的 OSSClient(ossConfigure.getEndpoint(),ossConfigure.getAccessKeyId(),
  35.                 ossConfigure.getAccessKeySecret());
  36.         //定义二级目录
  37.         String remoteFilePath = remotePath.substring(0 ,remotePath.length())。replaceAll(“\\\\”,“ / ”)+“ /”;
  38.         //创建上传对象的元数据
  39.         ObjectMetadata objectMetadata =  new  ObjectMetadata();
  40.         objectMetadata.setContentLength(fileContent.available());
  41.         objectMetadata.setContentEncoding(“utf-8” );
  42.         objectMetadata.setCacheControl(“no-cache” );
  43.         objectMetadata.setHeader(“Pragma” ,  “no-cache” );
  44.         objectMetadata.setContentType(contentType(fileName.substring(fileName.lastIndexOf(“。” ))));
  45.         objectMetadata.setContentDisposition(“inline; filename =”  + fileName);
  46.         //上传文件
  47.         ossClient.putObject(ossConfigure.getBucketName(),remoteFilePath + fileName,fileContent,objectMetadata);
  48.         //关闭OSSClient
  49.         ossClient.shutdown();
  50.         //关闭io流
  51.         fileContent.close();
  52.         return  ossConfigure.getAccessUrl()+  “/”  + remoteFilePath + fileName;
  53.     }
  54.     //下载文件
  55.     @SuppressWarnings “未使用”
  56.     public static void  downloadFile(OSSConfigure ossConfigure,String key,String filename)
  57.             抛出 OSSException,ClientException,IOException {
  58.         //初始化OSSClient
  59.         OSSClient ossClient =  新的 OSSClient(ossConfigure.getEndpoint(),ossConfigure.getAccessKeyId(),
  60.                 ossConfigure.getAccessKeySecret());
  61.         OSSObject对象= ossClient.getObject(ossConfigure.getBucketName(),key);
  62.         //获取ObjectMeta
  63.         ObjectMetadata meta = object.getObjectMetadata();
  64.         //获取对象的输入流
  65.         InputStream objectContent = object.getObjectContent();
  66.         ObjectMetadata objectData = ossClient.getObject(new  GetObjectRequest(ossConfigure.getBucketName(),key),
  67.                  文件(文件名));
  68.         //关闭数据流
  69.         objectContent.close();
  70.     }
  71.     / **
  72.      *根据key删除OSS服务器上的文件@Title:deleteFile @Description:@param @param
  73.      * ossConfigure @param @param filePath设定文件@return void返回类型@throws
  74.      * @抛出IOException 
  75.      * /
  76.     public static void  deleteFile(String filePath)  throws  IOException {
  77.         //加载配置文件,初始化OSSClient
  78.         OSSConfigure ossConfigure =  new  OSSConfigure(“/ system.properties );
  79.         OSSClient ossClient =  新的 OSSClient(ossConfigure.getEndpoint(),ossConfigure.getAccessKeyId(),
  80.                 ossConfigure.getAccessKeySecret());
  81.         filePath = filePath.substring(45 );
  82.         ossClient.deleteObject(ossConfigure.getBucketName(),filePath);
  83.     }
  84.     / **
  85.      *描述:判断OSS服务文件上传时文件的contentType @ Version1.0
  86.      * 
  87.      * @param FilenameExtension
  88.      *文件后缀
  89.      * @返回字符串
  90.      * /
  91.     public static  String contentType(String FileNameExtension){
  92.         if  (FilenameExtension.equals(“.BMP” )|| FilenameExtension.equals(“.bmp” )){
  93.             返回“image / bmp” ;
  94.         }
  95.         if  (FilenameExtension.equals(“.GIF” )|| FilenameExtension.equals(“.gif” )){
  96.             返回“image / gif” ;
  97.         }
  98.         if  (FilenameExtension.equals(“.JPEG” )|| FilenameExtension.equals(“.jpeg” )|| FilenameExtension.equals(“.JPG”
  99.                 || FilenameExtension.equals(“.jpg” )|| FilenameExtension.equals(“.PNG”
  100.                 || FilenameExtension.equals(“.png” )){
  101.             返回“image / jpeg” ;
  102.         }
  103.         if  (FilenameExtension.equals(“. HTML” )|| FilenameExtension.equals(“.html” )){
  104.             返回“text / html” ;
  105.         }
  106.         if  (FilenameExtension.equals(“.TXT” )|| FilenameExtension.equals(“.txt” )){
  107.             返回“text / plain” ;
  108.         }
  109.         if  (FilenameExtension.equals(“.VSD” )|| FilenameExtension.equals(“.vsd )){
  110.             返回“application / vnd.visio” ;
  111.         }
  112.         if  (FilenameExtension.equals(“.PPTX” )|| FilenameExtension.equals(“.pptx” )|| FilenameExtension.equals(“.PPT”
  113.                 || FilenameExtension.equals(“.ppt” )){
  114.             返回“application / vnd.ms-powerpoint” ;
  115.         }
  116.         if  (FilenameExtension.equals(“.DOCX” )|| FilenameExtension.equals(“.docx” )|| FilenameExtension.equals(“.DOC”
  117.                 || FilenameExtension.equals(“.doc” )){
  118.             返回“application / msword” ;
  119.         }
  120.         if  (FilenameExtension.equals(“.XML” )|| FilenameExtension.equals(“.xml” )){
  121.             返回“text / xml” ;
  122.         }
  123.         if  (FilenameExtension.equals(“. apk” )|| FilenameExtension.equals(“.APK” )){
  124.             返回“application / octet-stream” ;
  125.         }
  126.         返回“text / html” ;
  127.     }
  128. }

以上是主要代码,再贴一下我的控制器,我这里是做的应用程序文件上传

[java] 查看纯文本

  1. / **
  2.      * app文件上传
  3.      *
  4.      * @param imageFile
  5.      * @param请求
  6.      * @返回
  7.      * /
  8.     @RequestMapping (value =  “/ uploadApp” ,method = RequestMethod.POST)
  9.     @ResponseBody
  10.     public  ImportResponse uploadApp(@RequestParam “app” )MultipartFile appFile,VersionUpgrade versionUpgrade){
  11.         if  (versionUpgrade ==  null ){
  12.             返回 ImportResponse.fail(“上传失败!” );
  13.         }
  14.         尝试 {
  15.              //流转换将MultipartFile转换为所需的InputStream
  16.             CommonsMultipartFile cf =(CommonsMultipartFile)appFile;
  17.             DiskFileItem fi =(DiskFileItem)cf.getFileItem();
  18.             InputStream fileContent = fi.getInputStream();
  19.             String fileName = fi.getName();
  20.             字符串apkUrl = OSSManageUtil.uploadFile(fileContent,  “xxapp” ,fileName);
  21.             versionUpgrade.setApkUrl(apkUrl);
  22.             versionUpgrade.setLoginUserVw(curUser);
  23.             versionUpgradeManager.save(versionUpgrade);
  24.         }  捕获 (例外五){
  25.             log.error(“【app上传失败】:” ,e);
  26.             返回 ImportResponse.fail(“上传失败!” );
  27.         }
  28.         返回 ImportResponse.success(“上传成功!” );
  29.     }

以上就是全部内容了,都是API里面有的,因为自己做的过程中出现很多问题,所以分享给大家!

[java] 查看纯文本

  1. <p> <span lang = “zh-CN”  style = “font-size:18.6667px; font-family:新宋体” > </ span> </ p>
未经允许不得转载:阿里云代金券 » 阿里云oss服务器文件上传java

评论 抢沙发

  • 昵称 (必填)
  • 邮箱 (必填)
  • 网址

强烈推荐

高性能SSD云服务器ECS抗攻击,高可用云数据库RDS