Java 七牛雲存儲與下載


七牛雲的文件上傳和下載(私有空間)

1、本篇博客參考網址

https://blog.csdn.net/peaceful000/article/details/53171578

https://blog.csdn.net/albertfly/article/details/51499812

2、在pom.xml中添加需要的jar

<!--七牛雲上傳圖片服務-->
 <!-- https://mvnrepository.com/artifact/com.qiniu/qiniu-java-sdk -->
    <dependency>
      <groupId>com.qiniu</groupId>
      <artifactId>qiniu-java-sdk</artifactId>
      <version>7.0.8</version>
    </dependency>

3、詳細代碼

package com.qiniu.upload;

import com.qiniu.common.QiniuException;
import com.qiniu.http.Response;
import com.qiniu.storage.UploadManager;
import com.qiniu.util.Auth;
import com.qiniu.util.StringMap;
import com.squareup.okhttp.OkHttpClient;
import com.squareup.okhttp.Request;
import com.squareup.okhttp.ResponseBody;

import java.io.*;

public class QiniuUtil {

  //設置好賬號的ACCESS_KEY和SECRET_KEY
  String ACCESS_KEY = ""; //這兩個登錄七牛 賬號里面可以找到
  String SECRET_KEY = "";

  //要上傳的空間
  String bucketname = ""; //對應要上傳到七牛上 你的那個路徑(自己建文件夾 注意設置私有)
  //上傳到七牛后保存的文件名


  //密鑰配置
  Auth auth = Auth.create(ACCESS_KEY, SECRET_KEY);
  //創建上傳對象
  UploadManager uploadManager = new UploadManager();


  /**
   * 簡單上傳,使用默認策略,只需要設置上傳的空間名就可以了
   *
   * @param fileName 文件上傳至七牛雲空間的名稱
   * @return
   */
  public String getUpToken(String fileName) {
    //return auth.uploadToken(bucketname);
    //<bucket>:<key>,表示只允許用戶上傳指定key的文件。在這種格式下文件默認允許“修改”,已存在同名資源則會被本次覆蓋。
    //如果希望只能上傳指定key的文件,並且不允許修改,那么可以將下面的 insertOnly 屬性值設為 1。
    //第三個參數是token的過期時間
    return auth.uploadToken(bucketname, fileName, 3600, new StringMap().put("insertOnly", 0));
  }


  /**
   * 普通上傳
   *
   * @param filePath 文件路徑
   * @param fileName 文件上傳至七牛雲空間的名稱
   * @throws IOException
   */
  public void upload(String filePath, String fileName) {
    try {
      //調用put方法上傳
      Response res = uploadManager.put(filePath, fileName, getUpToken(fileName));
      //打印返回的信息
      System.out.println(res.bodyString());
    } catch (QiniuException e) {
      Response r = e.response;
      // 請求失敗時打印的異常的信息
      System.out.println(r.toString());
      try {
        //響應的文本信息
        System.out.println(r.bodyString());
      } catch (QiniuException e1) {
        //ignore
        e.printStackTrace();
      }
    }
  }

  /**
   * 獲取下載文件路徑,即:donwloadUrl
   *
   * @return
   */
  public String getDownloadUrl(String targetUrl) {
    String downloadUrl = auth.privateDownloadUrl(targetUrl);
    return downloadUrl;
  }


  /**
   * 文件下載
   *
   * @param targetUrl
   */
  public void download(String targetUrl) {
    //獲取downloadUrl
    String downloadUrl = getDownloadUrl(targetUrl);
    //本地保存路徑
    String filePath = "E:\\chen\\";
    download(downloadUrl, filePath);
  }


  /**
   * 通過發送http get 請求獲取文件資源
   *
   * @param url
   * @param filepath
   * @return
   */
  private static void download(String url, String filepath) {
    OkHttpClient client = new OkHttpClient();
    System.out.println(url);
    Request req = new Request.Builder().url(url).build();
    com.squareup.okhttp.Response resp = null;
    try {
      resp = client.newCall(req).execute();
      System.out.println(resp.isSuccessful());
      if (resp.isSuccessful()) {
        ResponseBody body = resp.body();
        InputStream is = body.byteStream();
        byte[] data = readInputStream(is);
        //判斷文件夾是否存在,不存在則創建
        File file = new File(filepath);
        if (!file.exists() && !file.isDirectory()) {
          System.out.println("===文件夾不存在===創建====");
          file.mkdir();
        }
        File imgFile = new File(filepath + "888.jpg");
        FileOutputStream fops = new FileOutputStream(imgFile);
        fops.write(data);
        fops.close();
      }
    } catch (IOException e) {
      e.printStackTrace();
      System.out.println("Unexpected code " + resp);
    }
  }

  /**
   * 讀取字節輸入流內容
   *
   * @param is
   * @return
   */
  private static byte[] readInputStream(InputStream is) {
    ByteArrayOutputStream writer = new ByteArrayOutputStream();
    byte[] buff = new byte[1024 * 2];
    int len = 0;
    try {
      while ((len = is.read(buff)) != -1) {
        writer.write(buff, 0, len);
      }
      is.close();
    } catch (IOException e) {
      e.printStackTrace();
    }
    return writer.toByteArray();
  }

  public static void main(String args[]) throws IOException {
    String fileName = "xiao.jpg";
    //上傳文件的路徑
    String FilePath = "C:\\Users\\ChenXiao\\Pictures\\Saved Pictures\\xiao.jpg";  //本地要上傳文件路徑
    // new QiniuUtil().upload(FilePath,fileName);

    //構造私有空間的需要生成的下載的鏈接;
    //格式: http://私有空間綁定的域名/空間下的文件名
    String targetUrl = "http://私有空間綁定的域名/下載文件名稱.后綴"
    new QiniuUtil().download(targetUrl);
  }

}

4、在七牛雲中拿到ACCESS_KEY和SECRET_KEY值和私有空間綁定的域名如下圖所示(注:在創建'私有空間'的時候我是創建在'華東地區'的,不知為何建在'華南地區'竟然上傳失敗!!!並未去深究緣由,有了解緣由的可在底下留言告知下,謝謝!!!)

七牛雲存儲01
七牛雲存儲02

5、至此,七牛雲進行文件的存儲和下載已然完成,在上述代碼和圖片中若是存在問題,請指出,謝謝!!!


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM