地质所 沉降监测网建设项目
chenhuan
2024-05-16 f992b4e508b358eba4170b1e9b1bb21319f7a3cd
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
package com.javaweb.oss.cloud;
 
import com.qiniu.http.Response;
import com.qiniu.storage.Configuration;
import com.qiniu.storage.Region;
import com.qiniu.storage.UploadManager;
import com.qiniu.util.Auth;
import com.javaweb.oss.domain.OssException;
import org.apache.commons.io.IOUtils;
 
import java.io.IOException;
import java.io.InputStream;
 
/**
 * 七牛云存储
 */
public class QiniuCloudStorageService extends CloudStorageService
{
    private UploadManager uploadManager;
 
    private String        token;
 
    public QiniuCloudStorageService(CloudStorageConfig config)
    {
        this.config = config;
        // 初始化
        init();
    }
 
    private void init()
    {
        uploadManager = new UploadManager(new Configuration(Region.autoRegion()));
        token = Auth.create(config.getQiniuAccessKey(), config.getQiniuSecretKey())
                .uploadToken(config.getQiniuBucketName());
    }
 
    @Override
    public String upload(byte[] data, String path)
    {
        try
        {
            Response res = uploadManager.put(data, path, token);
            if (!res.isOK())
            {
                throw new RuntimeException("上传七牛出错:" + res.toString());
            }
        }
        catch (Exception e)
        {
            throw new OssException("上传文件失败,请核对七牛配置信息");
        }
        return config.getQiniuDomain() + "/" + path;
    }
 
    @Override
    public String upload(InputStream inputStream, String path)
    {
        try
        {
            byte[] data = IOUtils.toByteArray(inputStream);
            return this.upload(data, path);
        }
        catch (IOException e)
        {
            throw new OssException("上传文件失败");
        }
    }
 
    @Override
    public String uploadSuffix(byte[] data, String suffix)
    {
        return upload(data, getPath(config.getQiniuPrefix(), suffix));
    }
 
    @Override
    public String uploadSuffix(InputStream inputStream, String suffix)
    {
        return upload(inputStream, getPath(config.getQiniuPrefix(), suffix));
    }
}