(入门)java实现七牛云图片文件的上传和下载

官网参考文档:https://developer.qiniu.com/kodo/sdk/1239/java

上传图片:

需要用到的参数:

1、AccessKey   (在“个人中心”-->“秘钥管理”中)

2、SecretKey     (在“个人中心”-->“秘钥管理”中)

3、存储空间名字(自己创建的)


1、创建一个Maven项目

pom.xml



    4.0.0

    com.qiniucloud
    qiniutest
    1.0-SNAPSHOT

    
        
            com.qiniu
            qiniu-java-sdk
            [7.2.0, 7.2.99]
        
    

UpLoad.java   上传

import com.google.gson.Gson;
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.storage.model.DefaultPutRet;
import com.qiniu.util.Auth;

public class UpLoad {

    public static void main(String[] args) {
        Configuration cfg = new Configuration(Zone.zone1());                //zong1() 代表华北地区
        UploadManager uploadManager = new UploadManager(cfg);

        String accessKey = "XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX";      //AccessKey的值
        String secretKey = "XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX";      //SecretKey的值
        String bucket = "liuning";                                          //存储空间名
        String localFilePath = "D:\\temp\\picture\\pictureFileName.png";     //上传图片路径

        String key = "456.png";                                               //在七牛云中图片的命名
        Auth auth = Auth.create(accessKey, secretKey);
        String upToken = auth.uploadToken(bucket);
        try {
            Response response = uploadManager.put(localFilePath, key, upToken);
            //解析上传成功的结果
            DefaultPutRet putRet = new Gson().fromJson(response.bodyString(), DefaultPutRet.class);
            System.out.println(putRet.key);
            System.out.println(putRet.hash);
        } catch (QiniuException ex) {
            Response r = ex.response;
            System.err.println(r.toString());
            try {
                System.err.println(r.bodyString());
            } catch (QiniuException ex2) {
                //ignore
            }
        }
}
    }

运行结果:

(入门)java实现七牛云图片文件的上传和下载_第1张图片


下载图片:

(转载自:https://blog.csdn.net/PEACEFUL000/article/details/53171578)

需要用到的参数:

1、AccessKey   (在“个人中心”-->“秘钥管理”中)

2、SecretKey     (在“个人中心”-->“秘钥管理”中)

3、存储空间名字(这个是自己创建的)

4、存储空间的外链默认域名,如下图所示:

(入门)java实现七牛云图片文件的上传和下载_第2张图片


DownLoad.java

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 = "XXXXXXXXXXXXXXXXXXXXX";          //AccessKey值
    String secretKey = "XXXXXXXXXXXXXXXXXXXXXXX";          //SecretKey值

    //密钥配置
    Auth auth = Auth.create(accessKey,secretKey);

    /**
     * 获取下载文件路径,即:donwloadUrl
     * @return
     */
    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:/temp/picture/";
        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();
        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 + "123.png");          //下载到本地的图片命名
                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();
    }


    /**
     * 主函数:测试
     * @param args
     */
    public static void main(String[] args) {
        //构造私有空间的需要生成的下载的链接;
        //格式: http://私有空间绑定的域名/空间下的文件名

        String targetUrl = "http://p7s6tmhce.bkt.clouddn.com/123.png";         //外链域名下的图片路径
        new DownLoad().download(targetUrl);
    }

}


你可能感兴趣的:((入门)java实现七牛云图片文件的上传和下载)