吾爱破解 - 52pojie.cn

 找回密码
 注册[Register]

QQ登录

只需一步,快速开始

查看: 4226|回复: 9
收起左侧

[Java 转载] 【笔记】对接七牛云demo

[复制链接]
萋小磊 发表于 2018-5-4 10:15
本帖最后由 wushaominkk 于 2018-5-4 10:54 编辑

[Java] 纯文本查看 复制代码
package cn.stone.demo.qiniu;

import java.util.HashMap;
import java.util.Map;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.google.gson.Gson;
import com.qiniu.common.QiniuException;
import com.qiniu.common.Zone;
import com.qiniu.http.Response;
import com.qiniu.storage.BucketManager;
import com.qiniu.storage.Configuration;
import com.qiniu.storage.UploadManager;
import com.qiniu.storage.model.BatchStatus;
import com.qiniu.storage.model.DefaultPutRet;
import com.qiniu.storage.model.FetchRet;
import com.qiniu.storage.model.FileInfo;
import com.qiniu.util.Auth;

/**
 * 
 * [url=home.php?mod=space&uid=686208]@AuThor[/url] xiaoshitou
 * [url=home.php?mod=space&uid=686237]@date[/url] 2018年5月4日 上午8:29:32
 * @version 1.0 说明: 将图片上传至七牛云
 */
@RestController
public class QiNiuUp {

        // 设置好账号的ACCESS_KEY和SECRET_KEY
        @Value("${QiNiu.ACCESS_KEY}")
        String accessKey;

        @Value("${QiNiu.SECRET_KEY}")
        String secretKey;

        // 要上传的空间名--
        @Value("${QiNiu.bucketname}")
        String bucket;

        @RequestMapping("/upFile")
        public String upFile() {
                // 构造一个带指定Zone对象的配置类
                Configuration cfg = new Configuration(Zone.zone0());
                UploadManager uploadManager = new UploadManager(cfg);

                // 指定上传的文件名 为空就是自动生成
                String key = "保存文件名.jpg";

                String localFilePath = "c:/headimg_dl.jpg";

                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
                        }
                }

                return "";
        }
        
        @RequestMapping("/getFile")
        public String getfile() {
                //构造一个带指定Zone对象的配置类
                Configuration cfg = new Configuration(Zone.zone0());
                //...其他参数参考类注释
                String key = "保存文件名.jpg";
                Auth auth = Auth.create(accessKey, secretKey);
                BucketManager bucketManager = new BucketManager(auth, cfg);
                FileInfo fileInfo = null ;
                try {
                        fileInfo = bucketManager.stat(bucket, key);
                    System.out.println(fileInfo.hash);
                    System.out.println(fileInfo.fsize);
                    System.out.println(fileInfo.mimeType);
                    System.out.println(fileInfo.putTime);
                    
                } catch (QiniuException ex) {
                    System.err.println(ex.response.toString());
                }
                return "";
        }
        
        @RequestMapping("/updateFile")
        public String updateFile() {
                //构造一个带指定Zone对象的配置类
                Configuration cfg = new Configuration(Zone.zone0());
                //...其他参数参考类注释
                String key = "保存文件名.jpg";
                String newMimeType = "xiaoshitou.jpg";
                Auth auth = Auth.create(accessKey, secretKey);
                BucketManager bucketManager = new BucketManager(auth, cfg);
                //修改文件类型
                try {
                    bucketManager.changeMime(bucket, key, newMimeType);
                } catch (QiniuException ex) {
                    System.out.println(ex.response.toString());
                }
                return newMimeType;
        }
        
        @RequestMapping("/deleteFile")
        public String deleteFile() {
                //构造一个带指定Zone对象的配置类
                Configuration cfg = new Configuration(Zone.zone0());
                //...其他参数参考类注释
                String key = "xiaoshitou.jpg";
                Auth auth = Auth.create(accessKey, secretKey);
                BucketManager bucketManager = new BucketManager(auth, cfg);
                try {
                    bucketManager.delete(bucket, key);
                } catch (QiniuException ex) {
                    //如果遇到异常,说明删除失败
                    System.err.println(ex.code());
                    System.err.println(ex.response.toString());
                }
                return key;
        }
        
        @RequestMapping("/getFileList")
        public String getFileList() {
                //构造一个带指定Zone对象的配置类
                Configuration cfg = new Configuration(Zone.zone0());
                //...其他参数参考类注释
                Auth auth = Auth.create(accessKey, secretKey);
                BucketManager bucketManager = new BucketManager(auth, cfg);
                //文件名前缀
                String prefix = "";
                //每次迭代的长度限制,最大1000,推荐值 1000
                int limit = 1000;
                //指定目录分隔符,列出所有公共前缀(模拟列出目录效果)。缺省值为空字符串
                String delimiter = "";
                //列举空间文件列表
                BucketManager.FileListIterator fileListIterator = bucketManager.createFileListIterator(bucket, prefix, limit, delimiter);
                while (fileListIterator.hasNext()) {
                    //处理获取的file list结果
                    FileInfo[] items = fileListIterator.next();
                    for (FileInfo item : items) {
                        System.out.println(item.key);
                        System.out.println(item.hash);
                        System.out.println(item.fsize);
                        System.out.println(item.mimeType);
                        System.out.println(item.putTime);
                        System.out.println(item.endUser);
                    }
                }
                return "";
        }
        
        @RequestMapping("/getForUrl")
        public String getForUrl() {
                //构造一个带指定Zone对象的配置类
                Configuration cfg = new Configuration(Zone.zone0());
                //...其他参数参考类注释
                String key = "qiniu.png";
                String remoteSrcUrl = "http://devtools.qiniu.com/qiniu.png";
                Auth auth = Auth.create(accessKey, secretKey);
                BucketManager bucketManager = new BucketManager(auth, cfg);
                //抓取网络资源到空间
                try {
                    FetchRet fetchRet = bucketManager.fetch(remoteSrcUrl, bucket, key);
                    System.out.println(fetchRet.hash);
                    System.out.println(fetchRet.key);
                    System.out.println(fetchRet.mimeType);
                    System.out.println(fetchRet.fsize);
                } catch (QiniuException ex) {
                    System.err.println(ex.response.toString());
                }
                return remoteSrcUrl;
        }
        
        @RequestMapping("/getFiles")
        public String getFiles() {
                //构造一个带指定Zone对象的配置类
                Configuration cfg = new Configuration(Zone.zone0());
                //...其他参数参考类注释
                Auth auth = Auth.create(accessKey, secretKey);
                BucketManager bucketManager = new BucketManager(auth, cfg);
                try {
                    //单次批量请求的文件数量不得超过1000
                    String[] keyList = new String[]{
                            "qiniu.jpg",
                            "xiaoshitou.jpg",
                            "Alan Walker - Faded.mp3",
                    };
                    BucketManager.BatchOperations batchOperations = new BucketManager.BatchOperations();
                    batchOperations.addStatOps(bucket, keyList);
                    Response response = bucketManager.batch(batchOperations);
                    BatchStatus[] batchStatusList = response.jsonToObject(BatchStatus[].class);
                    for (int i = 0; i < keyList.length; i++) {
                        BatchStatus status = batchStatusList[i];
                        String key = keyList[i];
                        System.out.print(key+"\t");
                        if (status.code == 200) {
                            //文件存在
                            System.out.println(status.data.hash);
                            System.out.println(status.data.mimeType);
                            System.out.println(status.data.fsize);
                            System.out.println(status.data.putTime);
                        } else {
                            System.out.println(status.data.error);
                        }
                    }
                } catch (QiniuException ex) {
                    System.err.println(ex.response.toString());
                }
                return "";
        } 
        
        @RequestMapping("/updateFiles")
        public String updateFiles() {
                //构造一个带指定Zone对象的配置类
                Configuration cfg = new Configuration(Zone.zone0());
                //...其他参数参考类注释
                Auth auth = Auth.create(accessKey, secretKey);
                BucketManager bucketManager = new BucketManager(auth, cfg);
                try {
                    //单次批量请求的文件数量不得超过1000
                    HashMap<String, String> keyMimeMap = new HashMap<>();
                    keyMimeMap.put("qiniu.jpg", "image/jpg");
                    keyMimeMap.put("qiniu.png", "image/png");
                    keyMimeMap.put("qiniu.mp4", "video/mp4");
                    BucketManager.BatchOperations batchOperations = new BucketManager.BatchOperations();
                    //添加指令
                    for (Map.Entry<String, String> entry : keyMimeMap.entrySet()) {
                        String key = entry.getKey();
                        String newMimeType = entry.getValue();
                        batchOperations.addChgmOp(bucket, key, newMimeType);
                    }
                    Response response = bucketManager.batch(batchOperations);
                    BatchStatus[] batchStatusList = response.jsonToObject(BatchStatus[].class);
                    int index = 0;
                    for (Map.Entry<String, String> entry : keyMimeMap.entrySet()) {
                        String key = entry.getKey();
                        System.out.print(key + "\t");
                        BatchStatus status = batchStatusList[index];
                        if (status.code == 200) {
                            System.out.println("change mime success");
                        } else {
                            System.out.println(status.data.error);
                        }
                        index += 1;
                    }
                } catch (QiniuException ex) {
                    System.err.println(ex.response.toString());
                }
                return "";
        }
        
        @RequestMapping("/deleteFiles")
        public String deleteFiles() {
                //构造一个带指定Zone对象的配置类
                Configuration cfg = new Configuration(Zone.zone0());
                //...其他参数参考类注释
                Auth auth = Auth.create(accessKey, secretKey);
                BucketManager bucketManager = new BucketManager(auth, cfg);
                try {
                    //单次批量请求的文件数量不得超过1000
                    String[] keyList = new String[]{
                            "qiniu.jpg",
                            "qiniu.mp4",
                            "qiniu.png",
                    };
                    BucketManager.BatchOperations batchOperations = new BucketManager.BatchOperations();
                    batchOperations.addDeleteOp(bucket, keyList);
                    Response response = bucketManager.batch(batchOperations);
                    BatchStatus[] batchStatusList = response.jsonToObject(BatchStatus[].class);
                    for (int i = 0; i < keyList.length; i++) {
                        BatchStatus status = batchStatusList[i];
                        String key = keyList[i];
                        System.out.print(key + "\t");
                        if (status.code == 200) {
                            System.out.println("delete success");
                        } else {
                            System.out.println(status.data.error);
                        }
                    }
                } catch (QiniuException ex) {
                    System.err.println(ex.response.toString());
                }
                return "";
        }
}

免费评分

参与人数 2吾爱币 +2 热心值 +1 收起 理由
范你好 + 1 + 1 我很赞同!
wushaominkk + 1 按标题格式要求发帖

查看全部评分

发帖前要善用论坛搜索功能,那里可能会有你要找的答案或者已经有人发布过相同内容了,请勿重复发帖。

 楼主| 萋小磊 发表于 2018-5-4 10:54
wushaominkk 发表于 2018-5-4 10:52
哪里看不懂,可以指出来,我修改一下

发帖标准规范:

原创帖:

         [原创源码]【语言类型】  +标题(明确帖子内容)  例:【原创源码】【易语言】+标题


非原创:

         [分类]【笔记】  +标题(明确帖子内容) 例:【易语言】【笔记】标题
         [分类]【转帖】  +标题(明确帖子内容) 例:【易语言】【转载】标题
         [分类]【分享】  +标题(明确帖子内容) 例:【易语言】【分享】标题

只明确了标题 还有哪不规范我也不知道了

免费评分

参与人数 1吾爱币 +3 热心值 +1 收起 理由
贴纸笔墨 + 3 + 1 小石头 还是不错的

查看全部评分

wushaominkk 发表于 2018-5-4 10:20
抱着丨枕头睡 发表于 2018-5-4 10:27
hairch 发表于 2018-5-4 10:37
七牛有官方demo吧。
 楼主| 萋小磊 发表于 2018-5-4 10:50
wushaominkk 发表于 2018-5-4 10:20
仔细看版规,按格式要求发帖

删了吧 哥们 看不懂版规

点评

哪里看不懂,可以指出来,我修改一下  详情 回复 发表于 2018-5-4 10:52
wushaominkk 发表于 2018-5-4 10:52
萋小磊 发表于 2018-5-4 10:50
删了吧 哥们 看不懂版规

哪里看不懂,可以指出来,我修改一下
wushaominkk 发表于 2018-5-4 10:56
QQ图片20180504105644.png
上面就是版规啊,下面是标题规范
 楼主| 萋小磊 发表于 2018-5-4 11:01
wushaominkk 发表于 2018-5-4 10:56
上面就是版规啊,下面是标题规范

有注释内容
鹤鹤鹤 发表于 2018-5-4 11:51
支持一下,虽然不懂
您需要登录后才可以回帖 登录 | 注册[Register]

本版积分规则

返回列表

RSS订阅|小黑屋|处罚记录|联系我们|吾爱破解 - LCG - LSG ( 京ICP备16042023号 | 京公网安备 11010502030087号 )

GMT+8, 2024-11-15 15:30

Powered by Discuz!

Copyright © 2001-2020, Tencent Cloud.

快速回复 返回顶部 返回列表