index.js 3.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105
  1. const _Http = getApp().globalData.http;
  2. Component({
  3. properties: {
  4. /* 最大上传数量 */
  5. maxCount: {
  6. type: String,
  7. value: 9
  8. },
  9. /* 文件上传类型限制 all media image file video */
  10. accept: {
  11. type: String,
  12. value: "all"
  13. },
  14. /* 上传回调 */
  15. uploadCallback: {
  16. type: Function
  17. },
  18. /* 文件夹ID */
  19. parentid: {
  20. type: String,
  21. value: wx.getStorageSync('siteP').appfolderid
  22. },
  23. changeState: {
  24. type: Function
  25. }
  26. },
  27. data: {
  28. fileList: []
  29. },
  30. methods: {
  31. /* 上传文件 */
  32. afterRead(event) {
  33. this.triggerEvent("changeState", true)
  34. for (let i = 0; i < event.detail.file.length; i++) {
  35. // 初始化数据
  36. let that = this,
  37. data = this.requestType(event.detail.file[i]);
  38. data.content.filename = data.content.filename ? data.content.filename : `${Date.now()}.${data.content.filetype}`;
  39. //发送请求
  40. wx.getFileSystemManager().readFile({
  41. filePath: event.detail.file[i].url,
  42. success: result => {
  43. //返回临时文件路径
  44. const fileData = result.data;
  45. _Http.basic(data).then(res => {
  46. if (res.code == '1') {
  47. that.uploadFile(res.data, fileData)
  48. } else {
  49. wx.showToast({
  50. title: `${fileData.filename}.${fileData.serialfilename}`,
  51. icon: "none"
  52. })
  53. }
  54. })
  55. },
  56. fail: console.error
  57. })
  58. }
  59. },
  60. /* 请求类型 */
  61. requestType(file) {
  62. //获取文件后缀
  63. var index = file.url.lastIndexOf(".");
  64. var ext = file.url.substr(index + 1);
  65. //文件名称
  66. return {
  67. "classname": "system.attachment.huawei.OBS",
  68. "method": "getFileName",
  69. "content": {
  70. "filename": file.name ? file.name.concat(Date.now(), ".").concat(ext) : Date.now() + '.' + ext,
  71. "filetype": ext,
  72. "parentid": this.data.parentid
  73. }
  74. }
  75. },
  76. /* 上传成功反馈 */
  77. uploadFile(res, data) {
  78. var that = this;
  79. wx.request({
  80. url: res.uploadurl,
  81. method: "PUT",
  82. data: data,
  83. header: {
  84. 'content-type': res.filetype == 'pdf' ? "application/pdf" : 'application/octet-stream'
  85. },
  86. success(a) {
  87. _Http.basic({
  88. "classname": "system.attachment.huawei.OBS",
  89. "method": "uploadSuccess",
  90. "content": {
  91. "serialfilename": res.serialfilename
  92. }
  93. }).then(s => {
  94. console.log("文件上传反馈", s)
  95. // if (s.msg != "成功") return;
  96. that.triggerEvent("uploadCallback", s.data.attachmentids);
  97. that.triggerEvent("changeState", false)
  98. }).catch(err => {
  99. console.log(err)
  100. })
  101. }
  102. })
  103. },
  104. }
  105. })