七牛云上传文件,删除,及转码

pom.xml中引入的依赖

<!--        七牛云-->
        <dependency>
            <groupId>com.qiniu</groupId>
            <artifactId>qiniu-java-sdk</artifactId>
            <version>[7.2.0, 7.2.99]</version>
        </dependency>
        <!--第三方依赖-->
        <dependency>
            <groupId>com.qiniu</groupId>
            <artifactId>qiniu-java-sdk</artifactId>
            <version>7.2.11</version>
            <scope>compile</scope>
        </dependency>


<dependency>
            <groupId>com.qiniu</groupId>
            <artifactId>happy-dns-java</artifactId>
            <version>0.1.4</version>
            <scope>compile</scope>
        </dependency>

 

 

 

七牛云存储工具类

package com.jeeplus.modules.utils;

import com.jeeplus.common.json.AjaxJson;
import com.qiniu.cdn.CdnManager;
import com.qiniu.common.QiniuException;
import com.qiniu.common.Zone;
import com.qiniu.http.Response;
import com.qiniu.storage.BucketManager;
import com.qiniu.storage.Configuration;
import com.qiniu.storage.UploadManager;
import com.qiniu.storage.persistent.FileRecorder;
import com.qiniu.util.Auth;
import com.qiniu.util.StringMap;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.nio.file.Paths;

public class QiNiuYunUploadUtil {

  // 设置需要操作的账号的AK,https://developer.qiniu.com/kodo/sdk/1239/java#upload-token
  private static final String ACCESS_KEY = "xxxx";

  // 设置需要操作的账号的SK,https://developer.qiniu.com/kodo/sdk/1239/java#upload-token
  private static final String SECRET_KEY = "xxxx";

  // 要上传的空间,https://developer.qiniu.com/kodo/sdk/1239/java#upload-token
  private static final String BUCKET = "xxxx";

  // 域名domainOfBucket
  private static final String DOMAIN_OF_BUCKET = "xxx.xxx.cn";

  // 华东是Zone.zone0(),华北是Zone.zone1(),华南是Zone.zone2(),北美是Zone.zoneNa0(), https://developer.qiniu.com/kodo/manual/1671/region-endpoint
  private static final Zone ZONE = Zone.zone1();   // todo


  public static Auth getAuth() {
    return Auth.create(ACCESS_KEY, SECRET_KEY);
  }

  /**
   * 获取上传凭证,https://developer.qiniu.com/kodo/sdk/1239/java#upload-flow
   */

  public static String getUploadCredential() {
    return getAuth().uploadToken(BUCKET);
  }
  public static String getUpToken(String bucketName, String key) {
            //insertOnly 如果希望只能上传指定key的文件,并且不允许修改,那么可以将下面的 insertOnly 属性值设为 1
             return Auth.create(ACCESS_KEY, SECRET_KEY).uploadToken(bucketName, key, 3600, new StringMap().put("insertOnly", 0));
       }

  /**
   * 构造一个带指定 Region 对象的配置类
   */
  public static UploadManager buildUploadManager() {
    return new UploadManager(new Configuration(ZONE));
  }


  /**
   * 文件上传
   *
   * @param filePath 需要上传的文件本地路径
   * @param fileNameKey   需要自定义保存在七牛云的文件名字,即上传文件后保存在七牛云服务器中的文件名(默认不指定的情况下,以文件内容的hash值作为文件名)
   */
  public static String fileUpload(String filePath, String fileNameKey) {

    try {
      String upToken = getUpToken(BUCKET, fileNameKey);
      Response response = buildUploadManager().put(filePath, fileNameKey, upToken);

      MyPutRet myPutRet = response.jsonToObject(MyPutRet.class);
//      DefaultPutRet putRet = new Gson().fromJson(response.bodyString(), DefaultPutRet.class);  // 解析上传成功的结果
      return buildPublicFileUrl(myPutRet.getKey());  // 返回的图片url
    } catch (Exception ex) {
      ex.printStackTrace();
    }
    return null;
  }

  /**
   * 根据文件名和域名返回图片的url,然后访问url直接就可以看到图片了
   *
   * @param fileNameKey 需要自定义保存在七牛云的文件名字,即上传文件后保存在七牛云服务器中的文件名(默认不指定的情况下,以文件内容的hash值作为文件名)
   */
  public static String buildPublicFileUrl(String fileNameKey) {

    try {

      String encodedFileName = URLEncoder.encode(fileNameKey, "utf-8");
      return String.format("%s/%s", DOMAIN_OF_BUCKET, encodedFileName);

    } catch (UnsupportedEncodingException e) {
      e.printStackTrace();
    }
    return null;
  }


  /**
   * 私有空间返回文件URL
   *
   * @param fileNameKey     需要自定义保存在七牛云的文件名字,即上传文件后保存在七牛云服务器中的文件名(默认不指定的情况下,以文件内容的hash值作为文件名)
   * @param expireInSeconds 过期时间,私有空间文件的访问链接超时时间,单位(秒)
   */
  public static String buildPrivateFileUrl(String fileNameKey, long expireInSeconds) {

    try {

      return getAuth().privateDownloadUrl(buildPublicFileUrl(fileNameKey), expireInSeconds);

    } catch (Exception e) {
      e.printStackTrace();
    }
    return null;
  }


  /**
   * 字节数组上传文件,然后返回文件的url,然后可以直接在公网上访问url看到文件了
   *
   * @param fileNameKey 需要自定义保存在七牛云的文件名字,即上传文件后保存在七牛云服务器中的文件名(默认不指定的情况下,以文件内容的hash值作为文件名)
   */
  public static String charArrayUpload(String fileNameKey, byte[] uploadBytes) {

    try {

      Response response = buildUploadManager().put(uploadBytes, fileNameKey, getUploadCredential());

//      DefaultPutRet putRet = new Gson().fromJson(response.bodyString(), DefaultPutRet.class);  // 解析上传成功的结果

      MyPutRet myPutRet = response.jsonToObject(MyPutRet.class);

      return buildPublicFileUrl(myPutRet.getKey());  // 返回的文件url

    } catch (Exception ex) {
      ex.printStackTrace();
    }
    return null;
  }


  /**
   * 断点续传
   *
   * @param fileNameKey   需要自定义保存在七牛云的文件名字,即上传文件后保存在七牛云服务器中的文件名(默认不指定的情况下,以文件内容的hash值作为文件名)
   * @param localFilePath 文件路径, 如果是Windows情况下,格式是 D:\\qiniu\\test.png
   */
  public static String breakPointUpload(String localFilePath, String fileNameKey) {

    try {

      // 如果是Windows情况下,格式是 D:\\qiniu\\test.png
      String localTempDir = Paths.get(System.getenv("java.io.tmpdir"), BUCKET).toString();

      // 设置断点续传文件进度保存目录
      FileRecorder fileRecorder = new FileRecorder(localTempDir);

      // 构造一个带指定Zone对象的配置类
      Configuration cfg = new Configuration(ZONE);
      UploadManager uploadManager = new UploadManager(cfg, fileRecorder);

      Response response = uploadManager.put(localFilePath, fileNameKey, getUploadCredential());
      // 解析上传成功的结果
//      DefaultPutRet putRet = new Gson().fromJson(response.bodyString(), DefaultPutRet.class);

      MyPutRet myPutRet = response.jsonToObject(MyPutRet.class);

      return buildPublicFileUrl(myPutRet.getKey());  // 返回的文件url

    } catch (Exception ex2) {
      ex2.printStackTrace();
    }
    return null;
  }

  /**
   * 删除文件
   * @param url  文件的名字
   * @return
   * @throws Exception
   */
  public static String delete(String url) throws Exception{
    Configuration cfg = new Configuration(Zone.zone1());
    String key = url;
    Auth auth = Auth.create(ACCESS_KEY, SECRET_KEY);
    BucketManager bucketManager = new BucketManager(auth, cfg);
    try {
      Response delete = bucketManager.delete(BUCKET, key);
      String s = delete.toString();
      return s;

    } catch (QiniuException ex) {
//如果遇到异常,说明删除失败
      System.err.println(ex.code());
      System.err.println(ex.response.toString());
      return null;

    }}
  /**
   * 刷新
   * @param url  文件的全路径
   * @throws QiniuException
   */
  public static void refresh(String url) throws QiniuException{
    String [] urls = {url};
    Auth auth = Auth.create(ACCESS_KEY, SECRET_KEY);
    CdnManager c = new CdnManager(auth);
    c.refreshUrls(urls);
  }


  // 测试
//  public static void main(String[] args) {
////    // 上传图片
////    DefaultPutRet defaultPutRet = fileUpload(Zone.zone2(), getUploadCredential(), "D:\\wulin.jpg", "微软微软微软认为");
////    String fileNameKey = defaultPutRet.key; // key是文件名
////
////    String s = buildPublicFileUrl(fileNameKey, "pygx2kf5f.bkt.clouddn.com");  // 返回的图片网址
////    System.out.println("ssss****" + s);
//
//    String url = fileUpload("D:\\1.png", "1");
//
//    System.out.println(url);
//
//  }
  //删除
//  public AjaxJson de(String url){
//    String[] split = url.split("/");
//    String name =split[1];
//    try {
//      Object delete = QiNiuYunUploadUtil.delete(url);
//      QiNiuYunUploadUtil.refresh(url);
//      return AjaxJson.success("成功").put("data",delete);
//    } catch (Exception e) {
//      e.printStackTrace();
//      return AjaxJson.error("失败");
//    }
//  }
//}
}

 

视频上传后转码

package com.jeeplus.modules.utils;

import com.qiniu.common.Zone;
import com.qiniu.processing.OperationManager;
import com.qiniu.storage.BucketManager;
import com.qiniu.storage.Configuration;
import com.qiniu.util.Auth;
import com.qiniu.util.StringMap;
import com.qiniu.util.UrlSafeBase64;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;

import com.qiniu.common.QiniuException;
import com.qiniu.http.Response;
import com.qiniu.storage.UploadManager;

public class UploadDemo {
    // 设置需要操作的账号的AK,https://developer.qiniu.com/kodo/sdk/1239/java#upload-token
    private static final String ACCESS_KEY = "PpNrmPOOjo6IpeasPnMPbYQ7k2OW9omYFFQDBJ7o";

    // 设置需要操作的账号的SK,https://developer.qiniu.com/kodo/sdk/1239/java#upload-token
    private static final String SECRET_KEY = "HXHPCvCIgQ_HSsvaChLEu9nANGd0QxOuvW8kN1zG";

    // 要上传的空间,https://developer.qiniu.com/kodo/sdk/1239/java#upload-token
    private static final String BUCKET = "qypd2021";

    // 域名domainOfBucket
    private static final String DOMAIN_OF_BUCKET = "file.zdcsr.cn";

    // 华东是Zone.zone0(),华北是Zone.zone1(),华南是Zone.zone2(),北美是Zone.zoneNa0(), https://developer.qiniu.com/kodo/manual/1671/region-endpoint
    private static final Zone ZONE = Zone.zone1();   // todo


    public static Auth getAuth() {
        return Auth.create(ACCESS_KEY, SECRET_KEY);
    }

    /**
     * 获取上传凭证,https://developer.qiniu.com/kodo/sdk/1239/java#upload-flow
     */

    public static String getUploadCredential() {
        return getAuth().uploadToken(BUCKET);
    }

    public static String getUpToken(String bucketName, String key) {
        //insertOnly 如果希望只能上传指定key的文件,并且不允许修改,那么可以将下面的 insertOnly 属性值设为 1
        return Auth.create(ACCESS_KEY, SECRET_KEY).uploadToken(bucketName, key, 3600, new StringMap().put("insertOnly", 0));
    }

    /**
     * 构造一个带指定 Region 对象的配置类
     */
    public static UploadManager buildUploadManager() {
        return new UploadManager(new Configuration(ZONE));
    }


    /**
     * 视频上传并转码
     *
     * @param filePath    需要上传的文件本地路径
     * @param fileNameKey 需要自定义保存在七牛云的文件名字,即上传文件后保存在七牛云服务器中的文件名(默认不指定的情况下,以文件内容的hash值作为文件名)
     */
    public static String upload(String filePath, String fileNameKey) {

        String newFileName = "new" + fileNameKey;//上传的文件名称

        try {
            //视频上传的参数
            String upToken = getUpToken(BUCKET, newFileName);
            Response response = buildUploadManager().put(filePath, newFileName, upToken);
            System.out.println("上传的结果:" + response);
            MyPutRet myPutRet = response.jsonToObject(MyPutRet.class);
            System.out.println("上传的文件名称:" + myPutRet.getKey());

            //视频转码
            new UploadDemo().transcoding(fileNameKey);

//      DefaultPutRet putRet = new Gson().fromJson(response.bodyString(), DefaultPutRet.class);  // 解析上传成功的结果
            return buildPublicFileUrl(fileNameKey);  // 返回的图片url
        } catch (Exception ex) {
            ex.printStackTrace();
        }
        return null;
    }

    /**
     * 根据文件名和域名返回图片的url,然后访问url直接就可以看到图片了
     *
     * @param fileNameKey
     * @return
     */
    public static String buildPublicFileUrl(String fileNameKey) {
        try {
            String encodedFileName = URLEncoder.encode(fileNameKey, "utf-8");
            return String.format("%s/%s", DOMAIN_OF_BUCKET, encodedFileName);
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        return null;
    }


    //获取授权对象
    Auth auth = Auth.create(ACCESS_KEY, SECRET_KEY);
    //执行操作的管理对象
    OperationManager operationMgr = new OperationManager(auth, new Configuration(Zone.zone1()));

    /**
     * 视频转码
     * @param keyName   //文件名称
     */
    void transcoding(String keyName) {
        String key = "new"+keyName;         //存储空间中视频的文件名称
        String newKey = keyName;        //转码后,另存的文件名称
        String pipeline = "admin_merge_radio";  //处理队列

        String saveAs = UrlSafeBase64.encodeToString(BUCKET + ":" + newKey);        //saveas接口 参数
        String fops = "avthumb/mp4/vcodec/libx264|saveas/" + saveAs;                //处理命令 avthumb 和 saveas 通过管道符 |  进行连接

        try {
            //执行转码和另存 操作
            String persistentId = operationMgr.pfop(BUCKET, key, fops, new StringMap().put("persistentPipeline", pipeline));
            System.out.println(persistentId);

        } catch (QiniuException e) {
            String errorCode = String.valueOf(e.response.statusCode);
            System.out.println(errorCode);
            e.printStackTrace();
        }
    }

    public static void main(String args[]) throws IOException {

        String filePath = "D:\\img\\test00008.mp4";
        String newKey = "test00008.mp4";

        String upload = new UploadDemo().upload(filePath, newKey);
        System.out.println("视频的URL----->:" + upload);
    }

}

 

posted @ 2022-03-10 16:26  知行IT讲堂  阅读(478)  评论(0编辑  收藏  举报