阿里雲oss 上傳與獲取圖片、視頻等

第一:上傳

依賴html

<dependency>
    <groupId>com.aliyun.oss</groupId>
    <artifactId>aliyun-sdk-oss</artifactId>
    <version>2.6.0</version>
</dependency>

<dependency>
    <groupId>com.aliyun</groupId>
    <artifactId>aliyun-java-sdk-core</artifactId>
    <version>3.3.1</version>
</dependency>

<dependency>
    <groupId>com.aliyun</groupId>
    <artifactId>aliyun-java-sdk-dysmsapi</artifactId>
    <version>1.0.0-SNAPSHOT</version>
    <systemPath>${lib.path}/aliyun-java-sdk-dysmsapi-1.0.0.jar
    </systemPath>
    <scope>system</scope>
</dependency>

Controller

@ApiOperation(value = "上傳圖片、文件、視頻等到阿里雲",response=String.class)
@RequestMapping(value = "/fileall/upload", method = RequestMethod.POST,consumes = MediaType.MULTIPART_FORM_DATA_VALUE)
public String upload1(@ApiParam(required = true,value = "表單形式提交的文件") @RequestParam MultipartFile file,
                      @ApiParam(required = true,value = "1,2,3") @RequestParam("type") String type){
    String image= null;
    try {
        image = OSSManageUtil.uploadFile1(file,type);
    } catch (IOException e) {
        e.printStackTrace();
    }
    return image;
}

工具類OSSManageUtiljava

private static OSSConfig ossConfig=OSSConfig.getInstance();
/**
 * 上傳圖片、文件、視頻等到阿里雲
 * @param file
 * @param type
 * @return
 */
public static String uploadFile1(MultipartFile file, String type) throws IOException {
   StringBuffer fileName = new StringBuffer();
   //獲取上傳文件的後綴名,如.png、.mp4 等等
   String fileExtension  = file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf("."));
   //文件流
   InputStream inputStream =new ByteArrayInputStream(file.getBytes());
   if("1".equals(type)){
      //指定目錄 如 xx111
      fileName.append(OssEnum.BUSINESS.getName());
   }
   if("2".equals(type)){
      //指定目錄 如 xx22
      fileName.append(OssEnum.INSTALLER.getName());
   }
   if("3".equals(type)){
      //指定目錄 如 xx3
      fileName.append(OssEnum.USERIMAGE_HEADIMAGE.getName());
   }
    //隨機生成文件名  如:指定目錄/隨機數.後綴名
   fileName.append( UUID.randomUUID().toString()+fileExtension);

   OSSClient ossClient=new OSSClient(ossConfig.getEndpoint(), ossConfig.getAccessKeyId(), ossConfig.getAccessKeySecret());
   //建立上傳Object的Metadata
   ObjectMetadata objectMetadata=new ObjectMetadata();
   objectMetadata.setContentLength(inputStream.available());
   objectMetadata.setContentEncoding("utf-8");
   objectMetadata.setCacheControl("no-cache");
   objectMetadata.setHeader("Pragma", "no-cache");
   objectMetadata.setContentType(contentType(fileName.substring(fileName.lastIndexOf(".")+1    )));//設置相似
   objectMetadata.setContentDisposition("inline;filename=" + fileName);//表示能在線播放
   //上傳文件 注意fileName若是沒有指定目錄,則上傳到根目錄下
   ossClient.putObject(ossConfig.getBucketName(), fileName.toString(), inputStream, objectMetadata);
   //上傳後訪問地址
   return ossConfig.getAccessUrl()+"/" +fileName;
}
/**
 * 根據key刪除OSS服務器上的文件
 */
public static void deleteFile(OSSConfig ossConfig,String filePath){
   OSSClient ossClient = new OSSClient(ossConfig.getEndpoint(),ossConfig.getAccessKeyId(), ossConfig.getAccessKeySecret());
   ossClient.deleteObject(ossConfig.getBucketName(), filePath);
   
}
/**
   * Description: 判斷OSS服務文件上傳時文件的contentType
   * @Version1.0
   * @param FilenameExtension 文件後綴
   * @return String 
   */
public static String contentType(String FilenameExtension){
if(FilenameExtension.equals("BMP")||FilenameExtension.equals("bmp")){return "image/bmp";}
if(FilenameExtension.equals("GIF")||FilenameExtension.equals("gif")){return "image/gif";}
if(FilenameExtension.equals("JPEG")||FilenameExtension.equals("jpeg")||
   FilenameExtension.equals("JPG")||FilenameExtension.equals("jpg")||  
   FilenameExtension.equals("PNG")||FilenameExtension.equals("png")){return "image/jpeg";}
if(FilenameExtension.equals("HTML")||FilenameExtension.equals("html")){return "text/html";}
if(FilenameExtension.equals("TXT")||FilenameExtension.equals("txt")){return "text/plain";}
if(FilenameExtension.equals("VSD")||FilenameExtension.equals("vsd")){return "application/vnd.visio";}
if(FilenameExtension.equals("PPTX")||FilenameExtension.equals("pptx")||
   FilenameExtension.equals("PPT")||FilenameExtension.equals("ppt")){return "application/vnd.ms-powerpoint";}
if(FilenameExtension.equals("DOCX")||FilenameExtension.equals("docx")||
   FilenameExtension.equals("DOC")||FilenameExtension.equals("doc")){return "application/msword";}
if(FilenameExtension.equals("XML")||FilenameExtension.equals("xml")){return "text/xml";}
if(FilenameExtension.equals("MP4")||FilenameExtension.equals("mp4")){
   return "video/mp4";
}
return "text/html";
}

枚舉類OssEnumapi

@Getter
public enum OssEnum {
    BUSINESS("xxx/"),//阿里雲中配置的文件目錄1
    INSTALLER("xxx/"),//文件目錄2
    USERIMAGE_SHAREQR("xxx/xx/"),//文件目錄3 多級目錄
    private String name;

    OssEnum(String name) {
        this.name = name;
    }
}

配置類OSSConfig服務器

@Date
public class OSSConfig {
   
   private static OSSConfig ossConfig=new OSSConfig();

   private static PropertiesLoader loader;
   
   private String endpoint;
   private String accessKeyId;
   private String accessKeySecret;
   private String bucketName;
   private String accessUrl;

   private OSSConfig() {
      loader=new PropertiesLoader("/properties/oss.properties");
      this.endpoint=getConfig("aliyun.oss.endpoint");
      this.accessKeyId=getConfig("aliyun.oss.accessKeyId");
      this.accessKeySecret=getConfig("aliyun.oss.accessKeySecret");
      this.bucketName=getConfig("aliyun.oss.bucketName");
      this.accessUrl=getConfig("aliyun.oss.accessUrl");
   }
   
   public static OSSConfig getInstance(){
      return ossConfig;
   }

   public static String getConfig(String key) {
      String value = loader.getProperty(key);
      return value;
   }
}

配置文件resources:properties/oss.propertiesapp

aliyun.oss.endpoint=oss-cn-beijing.aliyuncs.com
aliyun.oss.accessKeyId=xxx
aliyun.oss.accessKeySecret=xxx
aliyun.oss.bucketName=xxx
##"https://"+bucketName+endpoint
aliyun.oss.accessUrl=xxx

第二:獲取某個文件夾下的全部文件dom

Controlleride

@ApiOperation(value = "獲指定類型的全部圖片、文件、視頻等",response=String.class)
@RequestMapping(value = "/xxx", method = RequestMethod.GET)
public Result<List> getFile(@ApiParam(required = true,value = "1,2,3") @RequestParam("type") String type){
    List<String> imageList= null;
    try {
        imageList = OSSManageUtil.getdFile(type);
    } catch (Exception e) {
        e.printStackTrace();
    }
    return new Result(imageList);
}

工具類OSSManageUtil工具

/**
 * 獲取指定目錄下的全部文件地址
 * @param type
 * @return
 */
public static List<String> getdFile(String type) {
   ArrayList<String> imagesList = new ArrayList<>();
   if("3".equals(type)){
      //獲取xxx/xx/目錄下的全部文件
      ArrayList<String> fileListName = GetFileAllContent(OssEnum.USERIMAGE_HEADIMAGE.getName());
      fileListName.stream().forEach(e ->{
          //訪問地址拼接
         imagesList.add(ossConfig.getAccessUrl()+"/"+e);
      });
   }
   return imagesList;
}

/**
 * 獲取文件夾下的全部文件名;
 * @param FileName
 * @return
 */
public static ArrayList<String> GetFileAllContent(String FileName)
{
   OSSClient ossClient=new OSSClient(ossConfig.getEndpoint(), ossConfig.getAccessKeyId(), ossConfig.getAccessKeySecret());

   // 構造ListObjectsRequest請求
   ListObjectsRequest listObjectsRequest = new ListObjectsRequest(ossConfig.getBucketName());
   //Delimiter 設置爲 「/」 時,羅列該文件夾下的文件
   listObjectsRequest.setDelimiter("/");
   //Prefix 設爲某個文件夾名,羅列以此 Prefix 開頭的文件
   listObjectsRequest.setPrefix(FileName);

   ObjectListing listing = ossClient.listObjects(listObjectsRequest);
   ArrayList<String> list = new ArrayList<String>();
   // 遍歷全部Object:目錄下的文件
   for (OSSObjectSummary objectSummary : listing.getObjectSummaries()) {
      String key = objectSummary.getKey();
        //過濾指定目錄,由於獲取指定目錄下的文件,不只把目錄下的全部文件都返回,同時返回目錄文件
      if(key.equals(FileName)){
         continue;
      }
      list.add(key);
   }
   ossClient.shutdown();
   return list;
}
相關文章
相關標籤/搜索