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

index.js 1.6KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152
  1. import {get_filemd5sum, getBase64} from './utils.js'
  2. function FileUpLoadSdk () {
  3. const BYTES_PER_CHUNK = 1024 * 1024; // 每个文件切片大小定为1MB
  4. let offset = 0; //用于断点续传,默认为 0
  5. const IMAGE_TYPE_ERROR_CODE = 10
  6. const IMAGE_MULTIPART = '/multipart/upload/'
  7. const VIDOE_UPLOAD = '/upload/'
  8. postImage = (host, origin) => {
  9. if(!/\.(gif|jpg|jpeg|png|GIF|JPG|PNG)$/.test(origin)) {
  10. return IMAGE_TYPE_ERROR_CODE
  11. }
  12. var index1= origin.lastIndexOf(".");
  13. var index2= origin.length;
  14. let fileType= origin.substring(index1+1,index2)
  15. let fileSize = origin.size
  16. let md5 = get_filemd5sum(origin)
  17. let chunkNum = Math.ceil(this.fileSize / this.BYTES_PER_CHUNK); // 分片个数
  18. let base64Body = getBase64(origin)
  19. let xhr = new XMLHttpRequest()
  20. xhr.setRequestHeader('LINK_UPLOAD_FILE_SIZE',fileSize)
  21. xhr.setRequestHeader('LINK_UPLOAD_CHUNK_INDEX',1)
  22. xhr.setRequestHeader('LINK_UPLOAD_CHUNK_NUM',chunkNum)
  23. xhr.setRequestHeader('LINK_UPLOAD_CHUNK_SIZE',BYTES_PER_CHUNK)
  24. xhr.setRequestHeader('LINK_UPLOAD_OFFSET',offset)
  25. xhr.setRequestHeader('LINK_UPLOAD_FILE_MD5',md5)
  26. xhr.setRequestHeader('LINK_UPLOAD_FILE_TYPE',fileType)
  27. xhr.open('post', host+IMAGE_MULTIPART+origin, true)
  28. xhr.send(base64Body)
  29. xhr.onreadyStateChange = function () {
  30. if (xhr.readystate === 4) {
  31. if (xhr.status === 304 || (xhr.status >= 200 && xhr.status < 300)) {
  32. console.log('type: success, result: ', xhr.responseText)
  33. } else {
  34. console.log('type: error, errCode:', xhr.status)
  35. }
  36. }
  37. }
  38. }
  39. }