Fastdfs 断点续传

采用追加方式:

 1  public String[] uploadBreakpointFile(String group_name, String fileName, NameValuePair[] meta) {
 2         String[] results = null;
 3         File file = new File(fileName);
 4         long originalFileSize = file.length();
 5 
 6         byte[] file_buff;
 7 
 8         //NameValuePair[] vars = new NameValuePair[]{new NameValuePair("fileName", fileName), new NameValuePair("fileSize", String.valueOf(originalFileSize))};
 9         int number = (int) (originalFileSize / defaultSize), leftLength;
10         number = originalFileSize % defaultSize == 0 ? number : number + 1;
11         byte[] bytes;
12         try {
13             InputStream input = new FileInputStream(file);
14             file_buff = new byte[input.available()];
15             input.read(file_buff);
16 
17             if (originalFileSize > defaultSize) {
18 
19                 // 如果文件块大,则实现分块上传,需要准备一个空的文件
20 
21                 for (int i = 0; i < number; i++) {
22                     if (originalFileSize - (i) * defaultSize < defaultSize) {
23                         leftLength = (int) (originalFileSize - (i) * defaultSize);
24                         leftLength = leftLength < 0 ? (int) originalFileSize : leftLength;
25                         bytes = new byte[leftLength];
26                         if (i == 0) {
27                             results = storageClient.upload_appender_file(group_name, bytes, 0, leftLength, FilenameUtils.getExtension(fileName), meta);
28                         } else {
29                             /*采用追加的方式*/
30                             storageClient.append_file(results[0], results[1], bytes, 0, leftLength);
31                         }
32                     } else {
33                         bytes = new byte[(int) defaultSize];
34                         leftLength = (int) defaultSize;
35                         if (i == 0) {
36                             results = storageClient.upload_appender_file(group_name, bytes, 0, leftLength, FilenameUtils.getExtension(fileName), meta);
37                         } else {
38                             /*采用追加的方式*/
39                             storageClient.append_file(results[0], results[1], bytes, 0, leftLength);
40                         }
41                     }
42                 }
43                 //写入内容
44                 storageClient.modify_file(results[0], results[1], 0, file_buff, 0, file_buff.length);
45             } else {
46 //                 如果文件比默认的文件要小,则直接上传
47 
48                 results = storageClient.upload_file(group_name, file_buff, FilenameUtils.getExtension(fileName), meta);
49 
50             }
51         } catch (Exception e) {
52             e.printStackTrace();
53         }
54 
55         return results;
56 
57     }
posted on 2023-01-30 11:54  云淡风轻博客  阅读(599)  评论(0编辑  收藏  举报