上传插件,不包含上传的前端实现,只提供后端接口等,其他地方接入插件上传。包括上传进度、断点续传等

index.js 2.6KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091
  1. import { getFilemd5sum, getBase64 } from './testutil'
  2. const IMAGE_MULTIPART = '/multipart/upload/'
  3. const VIDEO_MULTIPART = '/upload/'
  4. function FileFactory(file) {
  5. this.offset = 0; //用于断点续传,默认为 0
  6. this.BYTES_PER_CHUNK = 1024 * 1024
  7. this.file = file
  8. this.fileSize = file.size
  9. this.fileType = file.type
  10. this.chunkNum = this.BYTES_PER_CHUNK > this.fileSize ? Math.ceil(this.fileSize / this.BYTES_PER_CHUNK):1
  11. this.chunkSize = this.BYTES_PER_CHUNK > this.fileSize ? this.fileSize:this.BYTES_PER_CHUNK
  12. }
  13. export default function UploadSdk(host, origin, token, file) {
  14. this.host = host
  15. this.origin = origin
  16. this.token = token
  17. this.file = file
  18. this.fileFactory = new FileFactory(file)
  19. this.generateMd5 = function (callback) {
  20. getFilemd5sum(this.file).then(result => {callback(result)})
  21. }
  22. this.generateBase64 = function (callback) {
  23. getBase64(this.file).then(result => {callback(result)})
  24. }
  25. //上传
  26. this.action = function() {
  27. this.generateMd5( (md5) => {
  28. this.md5 = md5
  29. this.generateBase64( (base64) => {
  30. this.base64Body = base64
  31. this.post(this.md5,this.base64Body,this.fileFactory)
  32. })
  33. })
  34. }
  35. //成功返回函数
  36. this.onSuccess = function () {
  37. return 'success'
  38. }
  39. //续传
  40. this.onContinue = function() {
  41. return 90
  42. }
  43. //错误
  44. this.onError = function() {
  45. return 200
  46. }
  47. this.post = function(md5,base64,fileFactory) {
  48. return new Promise((resolve, reject) => {
  49. let xhr = new XMLHttpRequest()
  50. xhr.open("POSt", this.host+IMAGE_MULTIPART+this.origin, true)
  51. xhr.withCredentials = true;
  52. xhr.setRequestHeader('Authorization', `Bearer ${this.token}`);
  53. xhr.setRequestHeader('Content-Type', 'application/json; charset=utf-8');
  54. xhr.setRequestHeader('Accept', 'application/json');
  55. xhr.setRequestHeader('LINK_UPLOAD_FILE_SIZE',fileFactory.fileSize)
  56. xhr.setRequestHeader('LINK_UPLOAD_CHUNK_INDEX',1+'')
  57. xhr.setRequestHeader('LINK_UPLOAD_CHUNK_NUM',fileFactory.chunkNum)
  58. xhr.setRequestHeader('LINK_UPLOAD_CHUNK_SIZE',fileFactory.chunkSize)
  59. xhr.setRequestHeader('LINK_UPLOAD_OFFSET',fileFactory.offset+'')
  60. xhr.setRequestHeader('LINK_UPLOAD_FILE_MD5',md5)
  61. xhr.setRequestHeader('LINK_UPLOAD_FILE_TYPE','jepg')
  62. xhr.send(JSON.stringify({body: base64}))
  63. xhr.onreadystatechange = function () {
  64. if (xhr.readyState === 4) {
  65. if (xhr.status === 304 || (xhr.status >= 200 && xhr.status < 300)) {
  66. resolve(xhr.responseText)
  67. } else {
  68. reject(xhr.status)
  69. }
  70. }
  71. }
  72. })
  73. }
  74. }