Spring Boot集成七牛云实现文件上传

1. 七牛云存储空间创建

注册认证七牛云账号后,在首页的管理控制台->选择空间管理->新建空间
Spring Boot集成七牛云实现文件上传_第1张图片
创建成功后,七牛云会自动分配一个外链域名,也可以自己定义:
Spring Boot集成七牛云实现文件上传_第2张图片
可以点击上图上传文件按钮,选中一个本地文件上传测试。

2. Spring Boot集成七牛云

  1. 添加maven依赖:
        <!--七牛云-->
        <dependency>
            <groupId>com.qiniu</groupId>
            <artifactId>qiniu-java-sdk</artifactId>
            <version>[7.2.0, 7.2.99]</version>
        </dependency>
  1. 七牛云配置类,密钥AK,SK配置信息在:个人中心->密钥管理 可查:
    Spring Boot集成七牛云实现文件上传_第3张图片

    @Component
    public class QiNiuUtil {
           
    	
    	//外链域名地址
        public static String qiniu_img_url_pre = "http://q8w1mid5i.bkt.clouddn.com/";
    	
    	//AccessKey
        public static String ACCESS_KEY = "CY39-W9tkMmp4p6AsYR9Bzcj5W-u459HRDhDRWkD";
    	
    	//SecretKey
        public static String SECRET_KEY = "PgeZCUjBhdryxp862kMHalFK3Up6ziqBaWJR2cLi";
    	
    	//存储空间名称
        public static String bucketname = "lijiageng";
        
        
        
        /**
         * 上传文件
         */
        public static String upload2Qiniu(FileInputStream file, String uploadFileName) {
           
            //构造一个带指定Zone对象的配置类,Zone.zone0()代表华东地区
            //zone2() 华南
            Configuration cfg = new Configuration(Zone.zone1());
            //...其他参数参考类注释
            UploadManager uploadManager = new UploadManager(cfg);
            //默认不指定key的情况下,以文件内容的hash值作为文件名
            String key = uploadFileName;
            Auth auth = Auth.create(ACCESS_KEY, SECRET_KEY);
            String upToken = auth.uploadToken(bucketname);
            try {
           
                Response response = uploadManager.put(file, key, upToken, null, null);
                //解析上传成功的结果
                String bodyString = response.bodyString();
                Map map = JSON.parseObject(bodyString, Map.class);
                String hash = (String) map.get("key");
                if (StringUtils.isNotEmpty(hash)) {
           
                    return qiniu_img_url_pre + uploadFileName;
                }
                System.out.println(response.bodyString());
                // 访问路径
                System.out.println(qiniu_img_url_pre + uploadFileName);
            } catch (QiniuException ex) {
           
                Response r = ex.response;
                System.err.println(r.toString());
                try {
           
                    System.err.println(r.bodyString());
                    return null;
                } catch (QiniuException ex2) {
           
                    //ignore
                    ex.printStackTrace();
                    return null;
                }
            }
            return null;
        }
    
        /**
         * 下载文件
         * @param url 文件在七牛云服务器上的地址
         * @return
         */
        public static byte[] downloadFromQNY(String url) {
           
             url ="http://q8w1mid5i.bkt.clouddn.com/893ab9c335cb472cb0a956840f75d46c.pdf";
            OkHttpClient client = new OkHttpClient();
            Request request = new Request.Builder().url(url).build();
            try {
           
                okhttp3.Response resp = client.newCall(request).execute();
                if (resp.isSuccessful()) {
           
                    ResponseBody body = resp.body();
                    InputStream inputStream = body.byteStream();
                    ByteArrayOutputStream writer = new ByteArrayOutputStream();
                    byte[] buff = new byte[1024 * 2];
                    int len = 0;
                    try {
           
                        while ((len = inputStream.read(buff)) != -1) {
           
                            writer.write(buff, 0, len);
                        }
                        inputStream.close();
                    } catch (Exception e) {
           
                        e.printStackTrace();
                    }
                    return writer.toByteArray();
                }
            } catch (Exception e) {
           
                e.printStackTrace();
            }
            return null;
        }
        
        
            public static void main(String[] args) throws FileNotFoundException {
           
    //        File file = new File("C:\\Users\\ljg\\Desktop\\BS\\xc-ui-pc-static-portal\\img\\page-1.jpg");
    //        FileInputStream fileInputStream = new FileInputStream(file);
    //        upload2Qiniu(fileInputStream,"123.jpg");
            downloadFromQNY(qiniu_img_url_pre + "893ab9c335cb472cb0a956840f75d46c.pdf");
        }
        
    }
    
    

你可能感兴趣的:(SpringBoot,Vue学习,java)