七牛云的使用——文件上传下载

1 开始

自己弄一个免费的云来玩一玩,刚接触还不懂,就自己上网多看看别人怎么操作的。
之前做项目用到了文件的上传下载,需要两个服务器,开发不方便,现在自己搞一个云服务,把文件上传到云,方便开发。
当然这个要自己多看文档,多学习啊~

七牛目前只支持一个请求上传一个文件,所以一次上传多个文件的话,就等同于一次发送多个请求,七牛不支持。
解决方案:
服务端,在上传的业务逻辑里加个循环
客户端,使用七牛提供的js sdk 实例:http://jssdk.demo.qiniu.io/
批量上传工具:
同步上传Windows客户端
命令行工具

官方文档参考:
从生成的 token 解析上传策略:https://developer.qiniu.com/kodo/kb/1488/from-the-generated-token-parsing-upload-strategy
公开 / 私有资源下载:https://developer.qiniu.com/kodo/manual/1655/download-public
如何上传base64编码图片到七牛云:https://developer.qiniu.com/kodo/kb/1326/how-to-upload-photos-to-seven-niuyun-base64-code
七牛云上传下载操作指南:https://developer.qiniu.com/kodo/kb/1336/upload-download-instructions

2 学习开始

1 上传

七牛云 要先实名认证,在“对象存储” 新建存储空间

  1. 需要提前准备的参数:AccessKey,SecretKey(七牛云个人中心的“密钥管理”中),存储的空间名字(自己创建的),存储空间的外链接默认域名,如下图:
    在这里插入图片描述
    在这里插入图片描述
  2. 需要使用到qiniu-java-sdk、happy-dns-java、okhttp3、okio、gson、okhttp、commons-codec等依赖
  3. 代码
    Qiniu.java
import java.io.IOException;
import com.qiniu.common.QiniuException;
import com.qiniu.common.Zone;
import com.qiniu.http.Response;
import com.qiniu.storage.Configuration;
import com.qiniu.storage.UploadManager;
import com.qiniu.util.Auth;
public class Qiniu{
    //设置好账号的ACCESS_KEY和SECRET_KEY
    String ACCESS_KEY = "2xxxxxxxxxxxxxxxxxx"; //这两个登录七牛 账号里面可以找到
    String SECRET_KEY = "xxxxxxxxxxxxxxxxxxxx";
    //要上传的空间
    String bucketname = "lixi"; //对应要上传到七牛上 你的那个路径(自己建文件夹 注意设置公开)
    //上传到七牛后保存的文件名
    String key = "testniu.txt";
    //上传文件的路径
    String FilePath = "d:\\test.txt";  //本地要上传文件路径
    //密钥配置
    Auth auth = Auth.create(ACCESS_KEY, SECRET_KEY);
    //创建上传对象
    Configuration cfg = new Configuration(Zone.autoZone());   //zong1() 代表华北地区
    UploadManager uploadManager = new UploadManager(cfg);
    //简单上传,使用默认策略,只需要设置上传的空间名就可以了
    public String getUpToken(){
        return auth.uploadToken(bucketname);
    }
    //普通上传
    public void upload() throws IOException{
        try {
            //调用put方法上传
            Response res = uploadManager.put(FilePath, key, getUpToken());
            //打印返回的信息
            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
            }
        }
    }
    public static void main(String args[]) throws IOException{
        new Qiniu().upload();
    }
}

需要修改参数:AK、SK、空间名bucketname、文件名file、文件路径filePath

这个工具类也是ok的,SimpleUpload.java

import java.io.File;
import java.io.FileInputStream;
import com.qiniu.common.QiniuException;
import com.qiniu.common.Zone;
import com.qiniu.http.Response;
import com.qiniu.storage.Configuration;
import com.qiniu.storage.UploadManager;
import com.qiniu.util.Auth;
import com.qiniu.util.Base64;
import com.qiniu.util.UrlSafeBase64;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
/**
 * 七牛 java sdk 简单上传,覆盖上传,文件上传
*/
public class SimpleUpload {
    //设置好账号的ACCESS_KEY和SECRET_KEY
    static String ACCESS_KEY = "2iDxxxxxxxxxxxxxxxxxxxx"; //这两个登录七牛 账号里面可以找到
    static String SECRET_KEY = "wHxOcXxxxxxxxxxxxxxxxx";
    // 上传空间
    static String bucketName = "lixi";
    Auth auth = Auth.create(ACCESS_KEY, SECRET_KEY);
    Configuration cfg = new Configuration(Zone.autoZone());   //zong1() 代表华北地区
    UploadManager uploadManager = new UploadManager(cfg);
    /**
     * 获取凭证
     * @param key 如果需要覆盖上传则设置此参数
     */
    public String getUpToken(String key) {
        return auth.uploadToken(bucketName);
    }
    /**
     * 上传方法1
     * @param filePath 文件路径  (也可以是字节数组、或者File对象)
     * @param key 上传到七牛上的文件的名称  (同一个空间下,名称【key】是唯一的)
     * @param bucketName 空间名称  (这里是为了获取上传凭证)
     */
    public void upload(String filePath, String key, String bucketName) {
        try {
            // 调用put方法上传
            Response res = uploadManager.put(filePath, key, getUpToken(key));
            // 打印返回的信息
            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 qe) {
                // ignore
            }
        }
    }
    /**
     * 上传方法2
     * @param file 文件
     * @param key 上传到七牛上的文件的名称  (同一个空间下,名称【key】是唯一的)
     */
    public void upload(File file, String key) {
        try {
            // 调用put方法上传
            Response res = uploadManager.put(file, key, getUpToken(key));
            // 打印返回的信息
            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 qe) {
                // ignore
            }
        }
    }
    /**
     * 上传方法3 覆盖上传
     * @param path 上传文件路径
     * @param key 文件名
     */
    public void overrideUpload(String path, String key) {
        try {
            String token = getUpToken(key);//获取 token
            Response response = uploadManager.put(path, key, token);//执行上传,通过token来识别 该上传是“覆盖上传”
            System.out.println(response.toString());
        } catch (QiniuException e) {
            System.out.println(e.response.statusCode);
            e.printStackTrace();
        }
    }
    // base64方式上传
    public void put64image(String filePath, String fileName, String key) throws Exception {
        FileInputStream fis = null;
        int l = (int) (new File(filePath).length());
        byte[] src = new byte[l];
        fis = new FileInputStream(new File(filePath));
        fis.read(src);
        String file64 = Base64.encodeToString(src, 0);
        String url = "http://upload.qiniu.com/putb64/" + l + "/key/" + UrlSafeBase64.encodeToString(fileName);
        RequestBody rb = RequestBody.create(null, file64);
        Request request = new Request.Builder().url(url).addHeader("Content-Type", "application/octet-stream")
                .addHeader("Authorization", "UpToken " + getUpToken(key)).post(rb).build();
        System.out.println(request.headers());
        OkHttpClient client = new OkHttpClient();
        okhttp3.Response response = client.newCall(request).execute();
        System.out.println(response);
    }
    /**
     * 主函数:程序入口,测试功能
     */
    public static void main(String[] args) {
        // 上传文件的路径,因为在Mac下,所以路径和windows下不同
        String filePath = "D:\\hua.jpg";
        // 上传到七牛后保存的文件名
        String key = "shuaer.jpg";
        // 这里的filepath可以直接替换成File如下注释所示
        // File file=new File(filePath);
        // new SimpleUpload().upload(file, key, bucketName);
        new SimpleUpload().upload(filePath, key, bucketName);
    }
}
报错:{“erreo”:“incorrect region,please use up-z2.qiniuup.com”}

开始看教程使用代码的时候,会报这样的错:
在这里插入图片描述
出错原因:
看字面意思,大概可能是我选的华南地区,地区不对造成的。

解决方案:

修改上传对象( 开始写的是Zone.Zone1() ),修改成:
Configuration cfg = new Configuration(Zone.autoZone()); //zong1() 代表华北地区

2 下载

下载私有空间文件思路:
1.创建自定义域名并绑定到一个空间上,即可通过该域名访问该空间下的文件资源;即:获取该文件资源的url,测试也可以用七牛提供的测试域名,但不建议使用到实际项目中。
2.获取该url后,需要使用七牛提供的auth对象,获取下载的url——-downloadUrl
3.通过http请求,根据downloadUrl 发送get请求进行下载。
https://blog.csdn.net/PEACEFUL000/article/details/53171578

代码如下:

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import com.qiniu.util.Auth;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import okhttp3.ResponseBody;
public class DownLoad {
    String accessKey = "2ixxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx";          //AccessKey值
    String secretKey = "wHxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx";          //SecretKey值
    //密钥配置
    Auth auth = Auth.create(accessKey,secretKey);
    /**
     * 获取下载文件路径,即:donwloadUrl
     */
    public String getDownloadUrl(String targetUrl) {
        String downloadUrl = auth.privateDownloadUrl(targetUrl);
        return downloadUrl;
    }
    /**
     * 下载
     */
    public void download(String targetUrl) {
        //获取downloadUrl
        String downloadUrl = getDownloadUrl(targetUrl);
        //本地保存路径
        String filePath = "D:/atemp/";
        download(downloadUrl, filePath);
    }
    /**
     * 通过发送http get 请求获取文件资源
     */
    private static void download(String url, String filepath) {
        OkHttpClient client = new OkHttpClient();
        System.out.println(url);
        Request req = new Request.Builder().url(url).build();
        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 imgFile = new File(filepath + "download123.jpg");   //下载到本地的图片命名
                FileOutputStream fops = new FileOutputStream(imgFile);
                fops.write(data);
                fops.close();
            }
        } catch (IOException e) {
            e.printStackTrace();
            System.out.println("Unexpected code " + resp);
        }
    }
    /**
     * 读取字节输入流内容
     */
    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) {
        //构造私有空间的需要生成的下载的链接;
        //格式: http://私有空间绑定的域名/空间下的文件名.文件后缀
        String targetUrl = "http://qbalabalaw.bkt.balan.com/shuaer.jpg";   //外链域名下的图片路径
        new DownLoad().download(targetUrl);
    }
}
发布了79 篇原创文章 · 获赞 7 · 访问量 1829

猜你喜欢

转载自blog.csdn.net/weixin_45044097/article/details/103637488
今日推荐