a
554325746@qq.com
2019-12-25 603cb36a5123e46656b06a5deb8d7ac7ff81307f
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
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
package com.basic.security.utils;
 
import android.content.ContextWrapper;
 
import com.basic.security.base.BaseApplication;
 
import org.csource.common.NameValuePair;
import org.csource.fastdfs.ClientGlobal;
import org.csource.fastdfs.StorageClient1;
import org.csource.fastdfs.StorageServer;
import org.csource.fastdfs.TrackerClient;
import org.csource.fastdfs.TrackerServer;
 
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.util.Properties;
 
/**
 * FastDFS文件上传,下载处理类
 *
 * @author sjw
 */
public class FastDFSUtil {
    private static final String TAG = "FastDFSUtil";
 
    //type是   jpg   png txt 之类的字符串
    public static void testUpload(String filePath, String type) {
        try {
            /*
             * 上传测试
             */
            String fdfs_client_path = new ContextWrapper(BaseApplication.getApplication().activity).getFilesDir().getAbsolutePath() + "/fdfs_client.properties";
            ClientGlobal.init(fdfs_client_path);
            fdfs_client_path = filePath;
            byte[] by = getBytes(fdfs_client_path);
            String fileName = filePath.substring(filePath.lastIndexOf("/") + 1, filePath.length());
            String resultPath = uploadFile(by, fileName, type);
//            System1.out.println(TAG + "上传后相对存储路径:" + resultPath);
//             System1.out.println("访问路径:"+PropertiesUtils.getInfo("fastdfs_url")+resultPath);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
 
    public static String upLoadVisitorPic(byte[] data, long time) {
        try {
            String fast_dfs_client_path = new ContextWrapper(BaseApplication.getApplication().activity).getFilesDir().getAbsolutePath() + "/fdfs_client.properties";
            ClientGlobal.init(fast_dfs_client_path);
            String fileName = DateUtil.formatTime(time, "yyyy-MM-dd HH:mm:ss");
            return uploadFile(data, fileName, "jpg");
        } catch (Exception e) {
//            e.printStackTrace();
            System1.out.println("FastDFSUtil.upLoadVisitorPic " + e.getMessage());
            return null;
        }
    }
 
    public static byte[] getBytes(String filePath) {
        byte[] buffer = null;
        try {
            File file = new File(filePath);
            FileInputStream fis = new FileInputStream(file);
            ByteArrayOutputStream bos = new ByteArrayOutputStream(1000);
            byte[] b = new byte[1000];
            int n;
            while ((n = fis.read(b)) != -1) {
                bos.write(b, 0, n);
            }
            fis.close();
            bos.close();
            buffer = bos.toByteArray();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return buffer;
    }
 
    /**
     * 文件上传
     *
     * @param pic  上传文件字节数组
     * @param name 文件名
     * @param ext  文件后缀名
     * @return FastDFS存储文件路径
     */
    public static String uploadFile(byte[] pic, String name, String ext) {
        String path;
        TrackerServer trackerServer = null;
        try {
//            System1.out.println(TAG + "上传文件名:" + name);
//            if (!getInfo("file_type_list").contains(ext)
//                    && !getInfo("file_type_list").toUpperCase().contains(ext)) {
//                System1.out.println("不支持" + ext + "类型文件上传!");
//                throw new RuntimeException("不支持" + ext + "类型文件上传!");
//            }
//            System1.out.println(TAG + "上传文件类型: " + ext);
            if (pic.length / 1024 / 1024 > 10) {
//                System1.out.println(TAG + "仅支持10MB以下文件上传!");
                throw new RuntimeException(TAG + "仅支持10MB以下文件上传!");
            }
//            System1.out.println(TAG + "文件大小:" + pic.length / 1024 + "KB");
            String fdfs_client_path = new ContextWrapper(BaseApplication.getApplication().activity).getFilesDir().getAbsolutePath();
            ClientGlobal.init(fdfs_client_path + "/fdfs_client.properties");
            TrackerClient trackerClient = new TrackerClient();
            trackerServer = trackerClient.getConnection();
//            System1.out.println(TAG + "tracker服务器连接成功! " + trackerServer.getInetSocketAddress());
            StorageServer storageServer = null;
            StorageClient1 storageClient1 = new StorageClient1(trackerServer, storageServer);
//            System1.out.println(TAG + "启动FastDFS客户端.... :" + storageClient1);
            NameValuePair[] meta_list = new NameValuePair[3];
            meta_list[0] = new NameValuePair("filename", name);
            meta_list[1] = new NameValuePair("fileext", ext);
            meta_list[2] = new NameValuePair("filesize", String.valueOf(pic.length));
            path = storageClient1.upload_file1(pic, ext, meta_list);
            if (null != path && !"".equals(path)) {
//                System1.out.println(TAG + "文件上传成功!   " + path);
                return path;
            } else {
//                System1.out.println(TAG + "文件上传失败!");
                throw new RuntimeException(TAG + "文件上传失败!");
            }
        } catch (Exception e) {
//            e.printStackTrace();
//            System1.out.println(TAG + "系统异常,文件上传失败!");
//            throw new RuntimeException(TAG + "系统异常,文件上传失败!" + e.getMessage());
            System1.out.println("FastDFSUtil.uploadFile " + e.getMessage());
        } finally {
            if (trackerServer != null) {
                try {
                    trackerServer.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return null;
    }
 
    /**
     * 文件下载 仅作为下载方式案例,项目中使用请参考cbs-dfs-demo
     *
     * @param fileUrl 文件上传后返回的存储路径,如:group3/M00/A1/64/CgIBSViAG6GAPLsAAATyXumgUaA302
     *                .jpg
     * @return 下载到本地的存储路径
     */
    @SuppressWarnings("unused")
    public static String downFile(String fileUrl) {
        if (null == fileUrl || "".equals(fileUrl)) {
//            System1.out.println("下载文件源路径为空!");
            return null;
        }
        BufferedInputStream dis = null;
        BufferedOutputStream fos = null;
        String filePath;
        try {
            // 存储下载文件的路径,默认存储在当前用户所在目录下
            filePath = System.getProperty("user.home") + File.separator
                    + fileUrl.substring(fileUrl.lastIndexOf("/") + 1);
//            System1.out.println("本地存储路径:" + filePath);
            File destFile = new File(filePath);
            if (!destFile.exists()) {
                destFile.createNewFile();
            }
            URL url = new URL(getInfo("http_head") + getInfo("fastdfs_vip")
                    + fileUrl);
//            System1.out.println("文件源路径:" + url);
            dis = new BufferedInputStream(url.openStream());
            fos = new BufferedOutputStream(new FileOutputStream(destFile));
            byte[] buff = new byte[2048];
            int bytesRead;
            while (-1 != (bytesRead = dis.read(buff, 0, buff.length))) {
                fos.write(buff, 0, bytesRead);
            }
//            System1.out.println("文件下载成功!");
        } catch (Exception e) {
//            System1.out.println("文件下载出现未知异常!");
            return null;
        } finally {
            if (dis != null) {
                try {
                    dis.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (fos != null) {
                try {
                    fos.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return filePath;
    }
 
    public static String getInfo(String code) throws Exception {
        ClassLoader classLoader = FastDFSUtil.class.getClassLoader();
        InputStream is = classLoader
                .getResourceAsStream("config/fdfs_client.conf");
        if (is == null) {
            is = classLoader.getResourceAsStream("fdfs_client.properties");
        }
        Properties prop = new Properties();
        if (is != null) {
            prop.load(is);
            return prop.getProperty(code);
        }
        return code;
    }
}