利用七牛云SDK实现文件的简单上传和下载

 首先要添加七牛云的依赖:

 

代码如下:

import com.google.gson.Gson;
import com.qiniu.common.QiniuException;
import com.qiniu.http.Response;
import com.qiniu.storage.Configuration;
import com.qiniu.storage.Region;
import com.qiniu.storage.UploadManager;
import com.qiniu.storage.model.DefaultPutRet;
import com.qiniu.util.Auth;
import lombok.extern.slf4j.Slf4j;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.ResponseBody;
import org.apache.commons.io.IOUtils;

import java.io.*;
import java.net.URLEncoder;

/**
 * @ProjectName: app-download
 * @Package: com.dongfeng.aliap
 * @ClassName: QiNiuOSSUtils
 * @Author: zhy
 * @Description: 七牛云存储
 * @Date: 2020/11/20 12:42
 * @Version: 1.0
 */
@Slf4j
public class QiNiuOSSUtils {
    private static final String ACCESS_KEY = "你的AK";

    private static final String SECRET_KEY = "你的SK";

    private static final String DOMAIN_BUCKET = "你的域名";

    private static final String BUCKET = "你的bucket";


    /**
     * 上传本地文件
     * 将异常抛出到上层,由上层进行处理
     *
     * @param path
     * @param localFilePath
     * @param key           七牛云端的key对应文件名称,此处的key需要加上路径
     * @return
     */
    public static String uploadLocalFile(String localFilePath, String path, String key) throws QiniuException, UnsupportedEncodingException {
        return uploadFile(new File(localFilePath), path, key);
    }

    /**
     * 利用七牛云上传文件
     *
     * @param path     文件需要保存的路径
     * @param file
     * @param filename 文件需要保存的名称
     * @return
     * @throws QiniuException
     */
    public static String uploadFile(File file, String path, String filename) throws QiniuException, UnsupportedEncodingException {
        //构造一个带指定 Region 对象的配置类
        Configuration cfg = new Configuration(Region.region1());
        //...其他参数参考类注释
        UploadManager uploadManager = new UploadManager(cfg);

        Auth auth = Auth.create(ACCESS_KEY, SECRET_KEY);
        String upToken = auth.uploadToken(BUCKET);
        //默认不指定key的情况下,以文件内容的hash值作为文件名
        Response response = uploadManager.put(file, String.format("%s/%s", path, filename), upToken);
        //解析上传成功的结果
        log.debug("uploadFile response:{}", response.bodyString());
        DefaultPutRet putRet = new Gson().fromJson(response.bodyString(), DefaultPutRet.class);
        log.debug("uploadFile response key: {}", putRet.key);
        log.debug("uploadFile response hash: {}", putRet.hash);
        return getDownloadUrl(path, filename);
    }

    /**
     * 七牛字节流上传
     *
     * @param path        在七牛云上保存的路径
     * @param inputStream
     * @param filename    文件保存的名字
     * @return
     */
    public static String uploadInputStream(InputStream inputStream, String path, String filename) throws QiniuException, UnsupportedEncodingException {
        //构造一个带指定 Region 对象的配置类,指定华北区
        Configuration cfg = new Configuration(Region.region1());
        //...其他参数参考类注释
        UploadManager uploadManager = new UploadManager(cfg);
//        String key = null;
        Auth auth = Auth.create(ACCESS_KEY, SECRET_KEY);
        String upToken = auth.uploadToken(BUCKET);
        //默认不指定key的情况下,以文件内容的hash值作为文件名
        Response response = uploadManager.put(inputStream, String.format("%s/%s", path, filename), upToken, null, null);
        log.debug("uploadInputStream response:{}", response.bodyString());
        DefaultPutRet putRet = new Gson().fromJson(response.bodyString(), DefaultPutRet.class);
        log.debug("uploadInputStream response key: {}", putRet.key);
        log.debug("uploadInputStream response hash: {}", putRet.hash);
        return getDownloadUrl(path, filename);
    }

    /**
     * 利用七牛云获取下载链接
     *
     * @param path     文件路径
     * @param filename 文件名称
     * @return
     * @throws UnsupportedEncodingException
     */
    public static String getDownloadUrl(String path, String filename) throws UnsupportedEncodingException {
        String encodedFileName = URLEncoder.encode(String.format("%s/%s", path, filename), "utf-8").replace("+", "%20");
        String publicUrl = String.format("%s/%s", DOMAIN_BUCKET, encodedFileName);
        Auth auth = Auth.create(ACCESS_KEY, SECRET_KEY);
        //1小时,可以自定义链接过期时间
        return auth.privateDownloadUrl(publicUrl, 60 * 60);
    }

    /**
     * 下载七牛云到指定文件中
     * @param path 七牛云中的路径
     * @param filename 七牛云中的文件名称
     * @param outputFile 输出到指定的文件
     * @throws IOException
     */
    public static void download(String path, String filename, String outputFile) throws IOException {
        OkHttpClient client = new OkHttpClient();
        Request request = new Request.Builder().url(getDownloadUrl(path, filename)).build();
        okhttp3.Response response = client.newCall(request).execute();
        InputStream in = null;
        FileOutputStream outputStream = null;
        try {
            if (response.isSuccessful()) {
                ResponseBody body = response.body();
                in = body.byteStream();
                outputStream = new FileOutputStream(outputFile);
                IOUtils.copy(in, outputStream);
            }
        } finally {
            if (null != in) {
                in.close();
            }
            if (null != outputStream){
                outputStream.close();
            }
        }
    }


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

        //上传字节流
//        try {
//            InputStream in = new FileInputStream("D:/qiniuyun.txt");
//            String url = uploadInputStream(in, "test", "qiniuyun5");
//            System.out.println(url);
//        } catch (FileNotFoundException | QiniuException e) {
//            e.printStackTrace();
//        }

        //上传文件
//        try {
//            String url = uploadLocalFile("D:/qiniuyun.txt", "test", "qiniuyun4");
//            System.out.println(url);
//        } catch (QiniuException e) {
//            e.printStackTrace();
//        }


        //获取下载链接
//        String download = getDownloadUrl("test", "qiniuyun4");
//        System.err.println(download);


        //访问链接地址,将输入流写入到文件
//        try {
//            download("test", "qiniuyun4", "D:/qiniuyun4.txt");
//        } catch (IOException e) {
//            e.printStackTrace();
//        }
    }
}

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
七牛云提供了丰富的工具和SDK,方便开发者在各种语言和平台上进行文件上传下载操作。以下是七牛云实现上传下载图片的工具包: 1. Qiniu Java SDKJava开发者可以使用Qiniu Java SDK上传下载文件,包括图片。该SDK提供了简单易用的API接口和丰富的功能,支持上传下载进度监听和断点续传等特性。 2. Qiniu Node.js SDK:Node.js开发者可以使用Qiniu Node.js SDK上传下载文件,包括图片。该SDK提供了简单易用的API接口和丰富的功能,支持上传下载进度监听和断点续传等特性。 3. Qiniu Python SDK:Python开发者可以使用Qiniu Python SDK上传下载文件,包括图片。该SDK提供了简单易用的API接口和丰富的功能,支持上传下载进度监听和断点续传等特性。 4. Qiniu PHP SDK:PHP开发者可以使用Qiniu PHP SDK上传下载文件,包括图片。该SDK提供了简单易用的API接口和丰富的功能,支持上传下载进度监听和断点续传等特性。 5. Qiniu Go SDK:Go开发者可以使用Qiniu Go SDK上传下载文件,包括图片。该SDK提供了简单易用的API接口和丰富的功能,支持上传下载进度监听和断点续传等特性。 以上是七牛云提供的一些常用语言的SDK,开发者可以根据需要选择相应的工具包来实现上传下载图片的功能。另外,七牛云还提供了丰富的文档和示例代码,方便开发者快速上手并完成开发任务。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值