12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091 |
- import { getFilemd5sum, getBase64 } from './testutil'
-
- const IMAGE_MULTIPART = '/multipart/upload/'
- const VIDEO_MULTIPART = '/upload/'
-
- function FileFactory(file) {
- this.offset = 0; //用于断点续传,默认为 0
- this.BYTES_PER_CHUNK = 1024 * 1024
- this.file = file
- this.fileSize = file.size
- this.fileType = file.type
- this.chunkNum = this.BYTES_PER_CHUNK > this.fileSize ? Math.ceil(this.fileSize / this.BYTES_PER_CHUNK):1
- this.chunkSize = this.BYTES_PER_CHUNK > this.fileSize ? this.fileSize:this.BYTES_PER_CHUNK
- }
-
- export default function UploadSdk(host, origin, token, file) {
-
- this.host = host
- this.origin = origin
- this.token = token
- this.file = file
- this.fileFactory = new FileFactory(file)
-
- this.generateMd5 = function (callback) {
- getFilemd5sum(this.file).then(result => {callback(result)})
- }
-
- this.generateBase64 = function (callback) {
- getBase64(this.file).then(result => {callback(result)})
- }
- //上传
- this.action = function() {
- this.generateMd5( (md5) => {
- this.md5 = md5
- this.generateBase64( (base64) => {
- this.base64Body = base64
- this.post(this.md5,this.base64Body,this.fileFactory)
- })
- })
- }
- //成功返回函数
- this.onSuccess = function () {
- return 'success'
- }
- //续传
- this.onContinue = function() {
- return 90
- }
- //错误
- this.onError = function() {
- return 200
- }
-
- this.post = function(md5,base64,fileFactory) {
- return new Promise((resolve, reject) => {
- let xhr = new XMLHttpRequest()
- xhr.open("POSt", this.host+IMAGE_MULTIPART+this.origin, true)
- xhr.withCredentials = true;
- xhr.setRequestHeader('Authorization', `Bearer ${this.token}`);
- xhr.setRequestHeader('Content-Type', 'application/json; charset=utf-8');
- xhr.setRequestHeader('Accept', 'application/json');
- xhr.setRequestHeader('LINK_UPLOAD_FILE_SIZE',fileFactory.fileSize)
- xhr.setRequestHeader('LINK_UPLOAD_CHUNK_INDEX',1+'')
- xhr.setRequestHeader('LINK_UPLOAD_CHUNK_NUM',fileFactory.chunkNum)
- xhr.setRequestHeader('LINK_UPLOAD_CHUNK_SIZE',fileFactory.chunkSize)
- xhr.setRequestHeader('LINK_UPLOAD_OFFSET',fileFactory.offset+'')
- xhr.setRequestHeader('LINK_UPLOAD_FILE_MD5',md5)
- xhr.setRequestHeader('LINK_UPLOAD_FILE_TYPE','jepg')
- xhr.send(JSON.stringify({body: base64}))
- xhr.onreadystatechange = function () {
- if (xhr.readyState === 4) {
- if (xhr.status === 304 || (xhr.status >= 200 && xhr.status < 300)) {
- resolve(xhr.responseText)
- } else {
- reject(xhr.status)
- }
- }
- }
- })
- }
- }
-
-
-
-
-
-
-
-
-
|