h5-uploader.js 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596
  1. let mask = document.querySelector(".mask");
  2. let fileDom = document.querySelector(".file");
  3. let tis = document.querySelector(".tis");
  4. let progress = document.querySelector(".tis-progress");
  5. let cancel = document.querySelector(".cancel-btn");
  6. let createUpload = (file, url, key='file', header = {},data = {}) => {
  7. console.log(`
  8. 上传地址:${url}\n
  9. 请求头:${JSON.stringify(header)}\n
  10. 参数:${JSON.stringify(data)}
  11. `);
  12. if (!url) {return;}
  13. tis.style.display = 'flex';
  14. let formData = new FormData();
  15. formData.append(key, file);
  16. for (let keys in data) {
  17. formData.append(keys, data[keys]);
  18. }
  19. let xhr = new XMLHttpRequest();
  20. xhr.open("POST", url, true);
  21. for (let keys in header) {
  22. xhr.setRequestHeader(keys, header[keys]);
  23. }
  24. xhr.upload.addEventListener("progress", function(event) {
  25. if(event.lengthComputable){
  26. let percent = Math.ceil(event.loaded * 100 / event.total) + "%";
  27. progress.innerText = `努力上传中..`;
  28. }
  29. }, false);
  30. xhr.ontimeout = function(){
  31. // xhr请求超时事件处理
  32. progress.innerText = '请求超时';
  33. setTimeout(()=>{
  34. tis.style.display = 'none';
  35. plus.webview.currentWebview().close();
  36. },1000);
  37. };
  38. xhr.onreadystatechange = (ev) => {
  39. if(xhr.readyState == 4) {
  40. console.log('status:'+xhr.status);
  41. if (xhr.status == 200) {
  42. if(xhr.responseText){
  43. //progress.innerText = '上传成功';
  44. console.log('返回数据:'+xhr.responseText);
  45. location.href = `callback?fileName=${escape(file.name)}&id=${escape(xhr.responseText)}`;
  46. }else{
  47. //progress.innerText = '上传格式不正确';
  48. console.log('返回数据:'+xhr.responseText);
  49. location.href = `callback?fileName=${escape(file.name)}&id=null`;
  50. }
  51. }
  52. else {
  53. progress.innerText = '上传失败了';
  54. }
  55. setTimeout(()=>{
  56. tis.style.display = 'none';
  57. plus.webview.currentWebview().close();
  58. },500);
  59. }
  60. };
  61. xhr.send(formData);
  62. cancel.addEventListener("click", ()=>{
  63. xhr.abort();
  64. plus.webview.currentWebview().close();
  65. });
  66. }
  67. mask.addEventListener("click", () => {
  68. plus.webview.currentWebview().close();
  69. });
  70. document.addEventListener('UniAppJSBridgeReady', () => {
  71. let {url,key,header,formData} = plus.webview.currentWebview();
  72. fileDom.addEventListener('change', (event) => {
  73. let file = fileDom.files[0];
  74. if(file.size > (1024*1024 * 50)) {
  75. plus.nativeUI.toast('单个文件请勿超过50M,请重新上传');
  76. return;
  77. }
  78. console.log(file.name);
  79. createUpload(file, url, key,header,formData);
  80. }, false);
  81. });