ChrisFuck před 5 roky
rodič
revize
f40e4a8dbe
2 změnil soubory, kde provedl 139 přidání a 157 odebrání
  1. 106
    54
      index.js
  2. 33
    103
      utils.js

+ 106
- 54
index.js Zobrazit soubor

@@ -1,90 +1,142 @@
1
-import { getFilemd5sum, getBase64 } from './testutil'
1
+import { getFilemd5sum } from './testutils'
2 2
 
3 3
 const IMAGE_MULTIPART = '/multipart/upload/'
4 4
 const VIDEO_MULTIPART = '/upload/'
5 5
 
6
+const IMAGE_TYPE_ERROR = 101
7
+const VIDOE_TYPE_ERROR = 102
8
+
9
+const UPLOAD_SUCCESS_CODE = 200
10
+const UPLOAD_FAILED_CODE = 400
11
+
6 12
 function FileFactory(file) {
7 13
   this.offset = 0; //用于断点续传,默认为 0
8 14
   this.BYTES_PER_CHUNK = 1024 * 1024
9 15
   this.file = file
10 16
   this.fileSize = file.size
11
-  this.fileType = file.type
17
+  this.fileType = (file.name.split('.')[1]).toLowerCase()
12 18
   this.chunkNum =  this.BYTES_PER_CHUNK > this.fileSize ? Math.ceil(this.fileSize / this.BYTES_PER_CHUNK):1
13 19
   this.chunkSize = this.BYTES_PER_CHUNK > this.fileSize ? this.fileSize:this.BYTES_PER_CHUNK
14 20
 }
15 21
 
22
+FileFactory.prototype.setOffset = function(offset) {
23
+  this.offset = offset
24
+}
25
+
16 26
 export default function UploadSdk(host, origin, token, file) {
17 27
   
18 28
   this.host = host
19 29
   this.origin = origin
20 30
   this.token = token
21 31
   this.file = file
22
-  this.fileFactory = new FileFactory(file)
23 32
 
24 33
   this.generateMd5 = function (callback) {
25 34
     getFilemd5sum(this.file).then(result => {callback(result)})
26 35
   }
27
-
28
-  this.generateBase64 = function (callback) {
29
-    getBase64(this.file).then(result => {callback(result)})
36
+  
37
+  this.imageUploadAction = function () {
38
+    return new Promise( (resolve, reject) => {
39
+      let fileFactory = new FileFactory(this.file)
40
+      if( !fileFactory.fileType.match('[(jpg)|(png)|(gif)]+$')) {
41
+        reject(IMAGE_TYPE_ERROR)
42
+      }
43
+      this.generateMd5( (md5) => {
44
+        this.md5 = md5
45
+        this.postImage(this.md5,fileFactory).then( res => {
46
+          resolve(res)
47
+        }).catch( (err) => {
48
+          reject(err)
49
+        })
50
+      }) 
51
+    })
30 52
   }
31
-  //上传
32
-  this.action = function() {
33
-    this.generateMd5( (md5) => {
34
-      this.md5 = md5
35
-      this.generateBase64( (base64) => {
36
-        this.base64Body = base64
37
-        this.post(this.md5,this.base64Body,this.fileFactory)
53
+
54
+  this.videoUploadAction = function () {
55
+    return new Promise( (resolve, reject) => {
56
+      if( !this.file.type.match('[(mp4)|(rmvb)|(flv)|(mpeg)|(avi)]+$')) {
57
+        reject(VIDOE_TYPE_ERROR)
58
+      }
59
+      this.postVideo().then( res => {
60
+        resolve(res)
61
+      }).catch( (err) => {
62
+        reject(err)
38 63
       })
39 64
     })
40 65
   }
41
-  //成功返回函数
42
-  this.onSuccess = function () {
43
-    return 'success'
44
-  }
45
-  //续传
46
-  this.onContinue = function() {
47
-    return 90
48
-  }
49
-  //错误
50
-  this.onError = function() {
51
-    return 200
66
+
67
+  this.postVideo = function() {
68
+    return new Promise( (resolve, reject) => {
69
+      let xhr = new XMLHttpRequest()
70
+      xhr.open('POST', 'http:'+this.host+VIDEO_MULTIPART+this.origin, true)
71
+      xhr.withCredentials = true;
72
+      xhr.setRequestHeader('Authorization', `Bearer ${this.token}`)
73
+      xhr.setRequestHeader('Content-type','application/json')
74
+      let fd = new FormData()
75
+      fd.append('file',this.file)
76
+      fd.append('code_rate','ld,sd,hd')
77
+      xhr.send(fd)
78
+      xhr.onreadystatechange = function () {
79
+        if (xhr.readyState === 4) {
80
+          let obj = JSON.parse(xhr.responseText)
81
+          if (xhr.status === 304 || (xhr.status >= 200 && xhr.status < 300)) {
82
+            resolve({
83
+              code: UPLOAD_SUCCESS_CODE,
84
+              url: obj.url,
85
+              msg: 'success'
86
+            })
87
+          } else {
88
+            reject({
89
+              code: UPLOAD_FAILED_CODE,
90
+              url:'',
91
+              msg:obj.message
92
+            })
93
+          }
94
+        }
95
+      }
96
+    })
52 97
   }
53 98
 
54
-  this.post = function(md5,base64,fileFactory) {
99
+  this.postImage = function(md5,fileFactory) {
100
+    const self = this
55 101
     return new Promise((resolve, reject) => {
56 102
       let xhr = new XMLHttpRequest()
57
-      xhr.open("POSt", this.host+IMAGE_MULTIPART+this.origin, true)
58
-        xhr.withCredentials = true;
59
-        xhr.setRequestHeader('Authorization', `Bearer ${this.token}`);
60
-        xhr.setRequestHeader('Content-Type', 'application/json; charset=utf-8');
61
-        xhr.setRequestHeader('Accept', 'application/json');
62
-        xhr.setRequestHeader('LINK_UPLOAD_FILE_SIZE',fileFactory.fileSize)
63
-        xhr.setRequestHeader('LINK_UPLOAD_CHUNK_INDEX',1+'')
64
-        xhr.setRequestHeader('LINK_UPLOAD_CHUNK_NUM',fileFactory.chunkNum)
65
-        xhr.setRequestHeader('LINK_UPLOAD_CHUNK_SIZE',fileFactory.chunkSize)
66
-        xhr.setRequestHeader('LINK_UPLOAD_OFFSET',fileFactory.offset+'')
67
-        xhr.setRequestHeader('LINK_UPLOAD_FILE_MD5',md5)
68
-        xhr.setRequestHeader('LINK_UPLOAD_FILE_TYPE','jepg')
69
-        xhr.send(JSON.stringify({body: base64}))
70
-        xhr.onreadystatechange = function () {
71
-          if (xhr.readyState === 4) {
72
-            if (xhr.status === 304 || (xhr.status >= 200 && xhr.status < 300)) {
73
-              resolve(xhr.responseText)
74
-            } else {
75
-              reject(xhr.status)
103
+      xhr.open('POSt', 'http:'+this.host+IMAGE_MULTIPART+this.origin, true)
104
+      xhr.withCredentials = true
105
+      xhr.setRequestHeader('Authorization', `Bearer ${this.token}`)
106
+      xhr.setRequestHeader('X-Upload-File-Size',fileFactory.fileSize)
107
+      xhr.setRequestHeader('X-Upload-Chunk-Index',1+'')
108
+      xhr.setRequestHeader('X-Upload-Chunk-Num',fileFactory.chunkNum)
109
+      xhr.setRequestHeader('X-Upload-Chunk-Size',fileFactory.chunkSize)
110
+      xhr.setRequestHeader('X-Upload-Offset',fileFactory.offset+'')
111
+      xhr.setRequestHeader('X-Upload-File-Md5',md5)
112
+      xhr.setRequestHeader('X-Upload-File-Type',fileFactory.fileType)
113
+      let fd = new FormData()
114
+      fd.append('file',this.file)
115
+      xhr.send(fd)
116
+      xhr.onreadystatechange = function () {
117
+        if (xhr.readyState === 4) {
118
+          let obj = JSON.parse(xhr.responseText)
119
+          if (xhr.status === 304 || (xhr.status >= 200 && xhr.status < 300)) {
120
+            
121
+            if(obj.status === 1) {
122
+              resolve({
123
+                code: UPLOAD_SUCCESS_CODE,
124
+                url: obj.url,
125
+                msg: 'success'
126
+              })
127
+            } else if (obj.status === 0) {
128
+              fileFactory.setOffset(obj.msg)
129
+              this.getAllResponseHeaders.postImage(md5,fileFactory)
76 130
             }
131
+          } else {
132
+            reject({
133
+              code: UPLOAD_FAILED_CODE,
134
+              url:'',
135
+              msg: obj.message
136
+            })
77 137
           }
78 138
         }
139
+      }
79 140
     })
80 141
   }
81
-}
82
-
83
-
84
-
85
-
86
-
87
-
88
-
89
-
90
-
142
+}

+ 33
- 103
utils.js Zobrazit soubor

@@ -1,110 +1,40 @@
1
-import { getFilemd5sum, getBase64 } from './testutil'
1
+import SparkMD5 from 'spark-md5'
2 2
 
3
-const IMAGE_MULTIPART = '/multipart/upload/'
4
-const VIDEO_MULTIPART = '/upload/'
5
-
6
-function FileFactory(file) {
7
-  this.offset = 0; //用于断点续传,默认为 0
8
-  this.BYTES_PER_CHUNK = 1024 * 1024
9
-  this.file = file
10
-  this.fileSize = file.size
11
-  this.fileType = file.type
12
-  this.chunkNum =  this.BYTES_PER_CHUNK > this.fileSize ? Math.ceil(this.fileSize / this.BYTES_PER_CHUNK):1
13
-  this.chunkSize = this.BYTES_PER_CHUNK > this.fileSize ? this.fileSize:this.BYTES_PER_CHUNK
14
-}
15
-
16
-export default function UploadSdk(host, origin, token, file) {
17
-  
18
-  this.host = host
19
-  this.origin = origin
20
-  this.token = token
21
-  this.file = file
3
+export function getFilemd5sum(ofile) {
4
+    return new Promise((resolve, reject) => {
5
+        let file = ofile;
6
+        let tmp_md5;
7
+        let blobSlice = File.prototype.slice || File.prototype.mozSlice || File.prototype.webkitSlice,
8
+            // file = this.files[0],
9
+            chunkSize = 8097152, // Read in chunks of 2MB
10
+            chunks = Math.ceil(file.size / chunkSize),
11
+            currentChunk = 0,
12
+            spark = new SparkMD5.ArrayBuffer(),
13
+            fileReader = new FileReader();
14
+
15
+        function loadNext()  {
16
+            var start = currentChunk * chunkSize,
17
+                end = ((start + chunkSize) >= file.size) ? file.size : start + chunkSize;
18
+            fileReader.readAsArrayBuffer(blobSlice.call(file, start, end));
19
+        }
22 20
 
23
-  this.generateMd5 = function (callback) {
24
-    getFilemd5sum(this.file).then(result => {callback(result)})
25
-  }
21
+        fileReader.onload = function (e) {
22
+            spark.append(e.target.result); // Append array buffer
23
+            currentChunk++;
26 24
 
27
-  this.generateBase64 = function (callback) {
28
-    getBase64(this.file).then(result => {callback(result)})
29
-  }
30
-  
31
-  this.imageUploadAction = function () {
32
-    return new Promise( (resolve, reject) => {
33
-      this.generateMd5( (md5) => {
34
-        this.md5 = md5
35
-        this.generateBase64( (base64) => {
36
-          this.base64Body = base64
37
-          let fileFactory = new FileFactory(file)
38
-            this.postImage(this.md5,this.base64Body,fileFactory).then( res => {
39
-              resolve(res)
40
-            }).catch( (err) => {
41
-              reject(err)
42
-            })
43
-        })
44
-      }) 
45
-    })
46
-  }
25
+            if (currentChunk < chunks) {
26
+                loadNext();
27
+            } else {
28
+                tmp_md5 = spark.end();
29
+                resolve(tmp_md5)
30
+            }
31
+        };
47 32
 
48
-  this.videoUploadAction = function () {
49
-    return new Promise( (resolve, reject) => {
50
-      this.postVideo().then( res => {
51
-        resolve(res)
52
-      }).catch( (err) => {
53
-        reject(err)
54
-      })
55
-    })
56
-  }
33
+        fileReader.onerror = function () {
34
+            reject('error');
35
+        };
57 36
 
58
-  this.postVideo = function() {
59
-    return new Promise( (resolve, reject) => {
60
-      let xhr = new XMLHttpRequest()
61
-      xhr.open("POSt", this.host+VIDEO_MULTIPART+this.origin, true)
62
-      xhr.open("POSt", this.host+IMAGE_MULTIPART+this.origin, true)
63
-      xhr.withCredentials = true;
64
-      xhr.setRequestHeader('Authorization', `Bearer ${this.token}`)
65
-      xhr.setRequestHeader('Content-Type', 'application/json; charset=utf-8')
66
-      xhr.setRequestHeader('Accept', 'application/json')
67
-      let fd = new FormData()
68
-      fd.append('file',this.file)
69
-      fd.append('code_rate','ld,sd,hd')
70
-      xhr.send(fd)
71
-      xhr.onreadystatechange = function () {
72
-        if (xhr.readyState === 4) {
73
-          if (xhr.status === 304 || (xhr.status >= 200 && xhr.status < 300)) {
74
-            resolve(xhr.responseText)
75
-          } else {
76
-            reject(xhr.status)
77
-          }
78
-        }
79
-      }
80
-    })
81
-  }
82
-
83
-  this.postImage = function(md5,base64,fileFactory) {
84
-    return new Promise((resolve, reject) => {
85
-      let xhr = new XMLHttpRequest()
86
-      xhr.open("POSt", this.host+IMAGE_MULTIPART+this.origin, true)
87
-      xhr.withCredentials = true
88
-      xhr.setRequestHeader('Authorization', `Bearer ${this.token}`)
89
-      xhr.setRequestHeader('Content-Type', 'application/json; charset=utf-8')
90
-      xhr.setRequestHeader('Accept', 'application/json')
91
-      xhr.setRequestHeader('LINK_UPLOAD_FILE_SIZE',fileFactory.fileSize)
92
-      xhr.setRequestHeader('LINK_UPLOAD_CHUNK_INDEX',1+'')
93
-      xhr.setRequestHeader('LINK_UPLOAD_CHUNK_NUM',fileFactory.chunkNum)
94
-      xhr.setRequestHeader('LINK_UPLOAD_CHUNK_SIZE',fileFactory.chunkSize)
95
-      xhr.setRequestHeader('LINK_UPLOAD_OFFSET',fileFactory.offset+'')
96
-      xhr.setRequestHeader('LINK_UPLOAD_FILE_MD5',md5)
97
-      xhr.setRequestHeader('LINK_UPLOAD_FILE_TYPE','jepg')
98
-      xhr.send(JSON.stringify({body: base64}))
99
-      xhr.onreadystatechange = function () {
100
-        if (xhr.readyState === 4) {
101
-          if (xhr.status === 304 || (xhr.status >= 200 && xhr.status < 300)) {
102
-            resolve(xhr.responseText)
103
-          } else {
104
-            reject(xhr.status)
105
-          }
106
-        }
107
-      }
37
+        
38
+        loadNext();
108 39
     })
109
-  }
110 40
 }