upload.js 9.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220
  1. var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
  2. var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
  3. if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
  4. else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
  5. return c > 3 && r && Object.defineProperty(target, key, r), r;
  6. };
  7. var __rest = (this && this.__rest) || function (s, e) {
  8. var t = {};
  9. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0)
  10. t[p] = s[p];
  11. if (s != null && typeof Object.getOwnPropertySymbols === "function")
  12. for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) {
  13. if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i]))
  14. t[p[i]] = s[p[i]];
  15. }
  16. return t;
  17. };
  18. import { isObject, SuperComponent, wxComponent } from '../common/src/index';
  19. import props from './props';
  20. import config from '../common/config';
  21. const { prefix } = config;
  22. const name = `${prefix}-upload`;
  23. let Upload = class Upload extends SuperComponent {
  24. constructor() {
  25. super(...arguments);
  26. this.externalClasses = [`${prefix}-class`];
  27. this.options = {
  28. multipleSlots: true,
  29. };
  30. this.data = {
  31. classPrefix: name,
  32. prefix,
  33. current: false,
  34. proofs: [],
  35. customFiles: [],
  36. customLimit: 0,
  37. };
  38. this.properties = props;
  39. this.controlledProps = [
  40. {
  41. key: 'files',
  42. event: 'success',
  43. },
  44. ];
  45. this.observers = {
  46. files(files) {
  47. this.handleLimit(files, this.data.max);
  48. },
  49. max(max) {
  50. this.handleLimit(this.data.customFiles, max);
  51. },
  52. gridConfig() {
  53. this.updateGrid();
  54. },
  55. };
  56. this.lifetimes = {
  57. ready() {
  58. this.handleLimit(this.data.customFiles, this.data.max);
  59. this.updateGrid();
  60. },
  61. };
  62. this.methods = {
  63. uploadFiles(files) {
  64. return new Promise((resolve) => {
  65. const task = this.data.requestMethod(files);
  66. if (task instanceof Promise) {
  67. return task;
  68. }
  69. resolve({});
  70. });
  71. },
  72. startUpload(files) {
  73. if (typeof this.data.requestMethod === 'function') {
  74. return this.uploadFiles(files)
  75. .then(() => {
  76. files.forEach((file) => {
  77. file.percent = 100;
  78. });
  79. this.triggerSuccessEvent(files);
  80. })
  81. .catch((err) => {
  82. this.triggerFailEvent(err);
  83. });
  84. }
  85. this.triggerSuccessEvent(files);
  86. this.handleLimit(this.data.customFiles, this.data.max);
  87. return Promise.resolve();
  88. },
  89. onAddTap() {
  90. const { mediaType, source } = this.properties;
  91. if (source === 'media') {
  92. this.chooseMedia(mediaType);
  93. }
  94. else {
  95. this.chooseMessageFile(mediaType);
  96. }
  97. },
  98. chooseMedia(mediaType) {
  99. const { config, sizeLimit, max } = this.data;
  100. wx.chooseMedia(Object.assign(Object.assign({ count: max === 0 ? 9 : max, mediaType }, config), { success: (res) => {
  101. const files = [];
  102. res.tempFiles.forEach((temp) => {
  103. const { size, fileType, tempFilePath, width, height, duration, thumbTempFilePath } = temp, res = __rest(temp, ["size", "fileType", "tempFilePath", "width", "height", "duration", "thumbTempFilePath"]);
  104. if (sizeLimit && size > sizeLimit) {
  105. wx.showToast({ icon: 'none', title: `${fileType === 'image' ? '图片' : '视频'}大小超过限制` });
  106. return;
  107. }
  108. const name = this.getRandFileName(tempFilePath);
  109. files.push(Object.assign({ name, type: this.getFileType(mediaType, tempFilePath, fileType), url: tempFilePath, size: size, width: width, height: height, duration: duration, thumb: thumbTempFilePath, percent: 0 }, res));
  110. });
  111. this.afterSelect(files);
  112. }, fail: (err) => {
  113. this.triggerFailEvent(err);
  114. }, complete: (res) => {
  115. this.triggerEvent('complete', res);
  116. } }));
  117. },
  118. chooseMessageFile(mediaType) {
  119. const { max, config, sizeLimit } = this.properties;
  120. wx.chooseMessageFile(Object.assign(Object.assign({ count: max, type: Array.isArray(mediaType) ? 'all' : mediaType }, config), { success: (res) => {
  121. const files = [];
  122. res.tempFiles.forEach((temp) => {
  123. const { size, type: fileType, path: tempFilePath } = temp, res = __rest(temp, ["size", "type", "path"]);
  124. if (sizeLimit && size > sizeLimit) {
  125. wx.showToast({ icon: 'none', title: `${fileType === 'image' ? '图片' : '视频'}大小超过限制` });
  126. return;
  127. }
  128. const name = this.getRandFileName(tempFilePath);
  129. files.push(Object.assign({ name, type: this.getFileType(mediaType, tempFilePath, fileType), url: tempFilePath, size: size, percent: 0 }, res));
  130. });
  131. this.afterSelect(files);
  132. }, fail: (err) => this.triggerFailEvent(err), complete: (res) => this.triggerEvent('complete', res) }));
  133. },
  134. afterSelect(files) {
  135. this._trigger('select-change', {
  136. files: [...this.data.customFiles],
  137. currentSelectedFiles: [files],
  138. });
  139. this._trigger('add', { files });
  140. this.startUpload(files);
  141. },
  142. };
  143. }
  144. onProofTap(e) {
  145. var _a;
  146. const { index } = e.currentTarget.dataset;
  147. wx.previewImage({
  148. urls: this.data.customFiles.filter((file) => file.percent !== -1).map((file) => file.url),
  149. current: (_a = this.data.customFiles[index]) === null || _a === void 0 ? void 0 : _a.url,
  150. });
  151. }
  152. handleLimit(customFiles, max) {
  153. while (max !== 0 && customFiles.length - max > 0) {
  154. customFiles.pop();
  155. }
  156. const proofs = [];
  157. customFiles.forEach((item) => {
  158. if (item.type !== 'video') {
  159. proofs.push(item.url);
  160. }
  161. });
  162. this.setData({
  163. customFiles,
  164. proofs,
  165. customLimit: max === 0 ? Number.MAX_SAFE_INTEGER : max - customFiles.length,
  166. });
  167. }
  168. triggerSuccessEvent(files) {
  169. this._trigger('success', { files: [...this.data.customFiles, ...files] });
  170. }
  171. triggerFailEvent(err) {
  172. this.triggerEvent('fail', err);
  173. }
  174. onFileClick(e) {
  175. const { file } = e.currentTarget.dataset;
  176. this.triggerEvent('click', { file });
  177. }
  178. getFileType(mediaType, tempFilePath, fileType) {
  179. if (fileType)
  180. return fileType;
  181. if (mediaType.length === 1) {
  182. return mediaType[0];
  183. }
  184. const videoType = ['avi', 'wmv', 'mkv', 'mp4', 'mov', 'rm', '3gp', 'flv', 'mpg', 'rmvb'];
  185. const temp = tempFilePath.split('.');
  186. const postfix = temp[temp.length - 1];
  187. if (videoType.includes(postfix.toLocaleLowerCase())) {
  188. return 'video';
  189. }
  190. return 'image';
  191. }
  192. getRandFileName(filePath) {
  193. const extIndex = filePath.lastIndexOf('.');
  194. const extName = extIndex === -1 ? '' : filePath.substr(extIndex);
  195. return parseInt(`${Date.now()}${Math.floor(Math.random() * 900 + 100)}`, 10).toString(36) + extName;
  196. }
  197. onDelete(e) {
  198. const { index } = e.currentTarget.dataset;
  199. this.deleteHandle(index);
  200. }
  201. deleteHandle(index) {
  202. const { customFiles } = this.data;
  203. const delFile = customFiles[index];
  204. this.triggerEvent('remove', { index, file: delFile });
  205. }
  206. updateGrid() {
  207. let { gridConfig = {} } = this.properties;
  208. if (!isObject(gridConfig))
  209. gridConfig = {};
  210. const { column = 4, width = 160, height = 160 } = gridConfig;
  211. this.setData({
  212. gridItemStyle: `width:${width}rpx;height:${height}rpx`,
  213. column: column,
  214. });
  215. }
  216. };
  217. Upload = __decorate([
  218. wxComponent()
  219. ], Upload);
  220. export default Upload;